標籤:
方法一:
iOS中有個叫端蓋(end cap)的概念,用來指定圖片中的哪一部分不用展開,上下左右不需要被展開的邊緣就稱為端蓋。
1 // use resizableImageWithCapInsets: and capInsets. 3 - (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight __TVOS_PROHIBITED;4 @property(nonatomic,readonly) NSInteger leftCapWidth __TVOS_PROHIBITED; // default is 0. if non-zero, horiz. stretchable. right cap is calculated as width - leftCapWidth - 15 @property(nonatomic,readonly) NSInteger topCapHeight __TVOS_PROHIBITED; // default is 0. if non-zero, vert. stretchable. bottom cap is calculated as height - topCapWidth - 1
1 // 展開地區距離左端寬度 2 NSInteger leftCapWidth = image.size.width * 0.5f; 3 // 展開地區距離頂端高度 4 NSInteger topCapHeight = image.size.height * 0.5f; 5 // 重新給image賦值 6 image = [image stretchableImageWithLeftCapWidth:leftCapWidth topCapHeight:topCapHeight];
方法二:
通過設定UIEdgeInsets的left、right、top、bottom來分別指定圖片展開地區距離左端寬度、右端寬度、頂端高度、底端高度
//通過設定UIEdgeInsets的left、right、top、bottom來分別指定圖片展開地區距離左端寬度、右端寬度、頂端高度、底端高度- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets NS_AVAILABLE_IOS(5_0); // create a resizable version of this image. the interior is tiled when drawn.
CGFloat top = 10; // 展開地區距離頂端高度CGFloat bottom = 10 ; // 展開地區距離底端高度CGFloat left = 20; // 展開地區距離左端寬度CGFloat right = 20; // 展開地區距離右端寬度UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);// 展開重新給image賦值image = [image resizableImageWithCapInsets:insets];
方法三:
在iOS6.0中,UIImage又提供了一個方法處理圖片展開,對比iOS5.0中的方法,多了一個UIImageResizingMode參數,用來指定展開的模式:UIImageResizingModeStretch:展開模式,通過展開UIEdgeInsets指定的矩形地區來填充圖片UIImageResizingModeTile:平鋪模式,通過重複顯示UIEdgeInsets指定的矩形地區來填充圖片
/*
*在iOS6.0中,UIImage又提供了一個方法處理圖片展開,對比iOS5.0中的方法,多了一個UIImageResizingMode參數,用來指定展開的模式:* UIImageResizingModeStretch:展開模式,通過展開UIEdgeInsets指定的矩形地區來填充圖片* UIImageResizingModeTile:平鋪模式,通過重複顯示UIEdgeInsets指定的矩形地區來填充圖片*/- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode NS_AVAILABLE_IOS(6_0); // the interior is resized according to the resizingMode
CGFloat top = 10; // 展開地區距離頂端高度CGFloat bottom = 10 ; //展開地區距離底端高度CGFloat left = 20; // 展開地區距離左端寬度CGFloat right = 20; // 展開地區距離右端寬度UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);// 展開後重新給image賦值 image = [image resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
iOS圖片展開的三種方法