拉伸圖片的幾種方式


問題:當圖片比較小,而圖片框.或者按鈕,比較大,圖片填充整個按鈕會導致變形,通過拉伸圖片可以使得雖然拉伸而不變形.

拉伸處理后:

方式1.通過resizableImageWithCapInsets:resizingMode方法.

- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode NS_AVAILABLE_IOS(6_0); // the interior is resized according to the resizingMode

實現代碼:

    UIImage *img = [UIImage imageNamed:@"RedButton"];
    
    CGFloat h = img.size.height * 0.5;
    CGFloat l = img.size.height * 0.5;

    UIImage *newImg = [img resizableImageWithCapInsets:UIEdgeInsetsMake(h,l, h, l) resizingMode:UIImageResizingModeStretch];
    self.imgView.image = newImg;

參數說明:

(UIEdgeInsets)capInsets:不拉伸的部分,設置到上下左右不拉伸的距離,只拉伸中間一小塊或者一個點.
(UIImageResizingMode)resizingMode:這是一個枚舉值,表示以什么樣的方式拉伸圖片.
兩種樣式:
 UIImageResizingModeTile,//通過重復鋪內部的一小塊區域填充新圖片的內部區域
//The image is tiled when it is resized. In other words, the interior region of the original image will be repeated to fill in the interior region of the newly resized image.
 UIImageResizingModeStretch,//通過縮放內部的圖片內部的區域填充新圖片的內部區域
//The image is stretched when it is resized. In other words, the interior region of the original image will be scaled to fill in the interior region of the newly resized imaged.

方式2:通過故事板,修改,x,y,width,height值.通過xy確定一個點,通過width,heigth確定寬高,由此獲得圖片中一小塊內容,從而對這一小塊內容進行拉伸

這是UIView的一個屬性

@property(nonatomic)                 CGRect            contentStretch NS_DEPRECATED_IOS(3_0,6_0) __TVOS_PROHIBITED; // animatable. default is unit rectangle {{0,0} {1,1}}. Now deprecated: please use -[UIImage resizableImageWithCapInsets:] to achieve the same effect.

 這個屬性已經過期了,官方建議使用方式一.

#方式3:通過方法stretchableImageWithLeftCapWidth:topCapHeight.這是UIImage的一個方法

- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight __TVOS_PROHIBITED;

方法說明:

@interface UIImage(UIImageDeprecated)//不贊成使用

// use resizableImageWithCapInsets: and capInsets.

- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight __TVOS_PROHIBITED;
@property(nonatomic,readonly) NSInteger leftCapWidth __TVOS_PROHIBITED;   // default is 0. if non-zero, horiz. stretchable. right cap is calculated as width - leftCapWidth - 1
//如果leftCapWidth不為0,可以水平拉伸,右邊覆蓋部分范圍等於( width - leftCapWidth - 1 )
@property(nonatomic,readonly) NSInteger topCapHeight __TVOS_PROHIBITED; // default is 0. if non-zero, vert. stretchable. bottom cap is calculated as height - topCapWidth - 1 //如果topCapHeight不為0,可以上下拉伸,下邊覆蓋部分范圍等於(height - topCapWidth - 1) @end

#實現代碼

    UIImage *img = [UIImage imageNamed:@"RedButton"];

    CGFloat h = img.size.height * 0.5;
    CGFloat l = img.size.height * 0.5;

    UIImage *newImg = [img stretchableImageWithLeftCapWidth:h topCapHeight:l];
    self.imgView.image = newImg;

#方式4;

總結:

說是四種方式,說白了還是一種方式,按照自己的方式拉伸圖片.通常,將整個圖片拉伸會導致邊角變形,這幾種拉伸方式都是限定被拉伸區域從而實現拉伸而邊角不變形.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM