UIButton图片拉伸方法(很多需要按钮的地方我们只需要一张小图来进行缩放)

系统提供3种方法来满足不同的需求(直接上代码):


#import <UIKit/UIKit.h>

@interface UIImage (Common)

/**
 *  根据图片名返回一张能自由拉伸的图片(图片缩放)
 */
+ (UIImage *)resizedImage:(NSString *)name;

/**
 *iOS5提供的方法
 */
+(UIImage*)resizeImageWithIOS5Method:(NSString*)imageName;

/**
 *iOS6提供的方法,从中间开始缩放
 */
+(UIImage*)resizeImageWithIOS6Method:(NSString*)name;

@end

.m的的实现方法:

#import "UIImage+Common.h"

@implementation UIImage (Common)

+ (UIImage *)resizedImage:(NSString *)name
{
    UIImage *image = [UIImage imageNamed:name];
    return [image stretchableImageWithLeftCapWidth:image.size.width * 0.5 topCapHeight:image.size.height * 0.5];
}

/**
 *iOS5提供的方法
 */
+(UIImage*)resizeImageWithIOS5Method:(NSString*)imageName{
    UIImage *image = [UIImage imageNamed:imageName];
    //顶端盖的高度
    CGFloat top = 25;
    CGFloat bottom = 25;//低端盖的高度
    CGFloat left = 10;//左端盖的高度
    CGFloat right = 10;//右端盖的高度
    UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
    //伸缩后重新赋值
    return [image resizableImageWithCapInsets:insets];
}

/**
 *iOS6提供的方法
 *@param  UIImageResizingModeStretch:拉伸模式,通过拉伸UIEdgeInsets指定的矩形区域来填充图片
 *@param  UIImageResizingModeTile:平铺模式,通过重复显示UIEdgeInsets指定的矩形区域来填充图片
 */
+(UIImage*)resizeImageWithIOS6Method:(NSString*)name{
    UIImage *image = [UIImage imageNamed:name];
    //顶端盖的高度
    CGFloat top = 10;
    CGFloat bottom = 10;//低端盖的高度
    CGFloat left = 10;//左端盖的高度
    CGFloat right = 10;//右端盖的高度
    UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
    //指定为拉伸模式,伸缩后重新赋值
    return [image resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
}

 

posted @ 2016-06-28 10:47  Crazy_ZY  阅读(2118)  评论(0编辑  收藏  举报