系統提供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]; }
