問題:當圖片比較小,而圖片框.或者按鈕,比較大,圖片填充整個按鈕會致使變形,經過拉伸圖片能夠使得雖然拉伸而不變形.atom
拉伸處理後:spa
方式1.經過resizableImageWithCapInsets:resizingMode方法.code
- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode NS_AVAILABLE_IOS(6_0); // the interior is resized according to the resizingMode
實現代碼:blog
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肯定寬高,由此得到圖片中一小塊內容,從而對這一小塊內容進行拉伸it
這是UIView的一個屬性io
@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.
這個屬性已通過期了,官方建議使用方式一.table
#方式3:經過方法stretchableImageWithLeftCapWidth:topCapHeight.這是UIImage的一個方法class
- (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;
總結:
說是四種方式,說白了仍是一種方式,按照本身的方式拉伸圖片.一般,將整個圖片拉伸會致使邊角變形,這幾種拉伸方式都是限定被拉伸區域從而實現拉伸而邊角不變形.