? 今天開發(fā)過程中遇到了圖片拉伸的問題棕兼。 一般情況下
- (UIImage*)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode
下面上效果圖與切圖障斋。
來說一下我處理這個圖片的方法贞瞒。
1.先拉伸菱形左邊契邀,保持右邊不變摆寄。
2.改變圖片的Size。
3.拉伸圖片右邊坯门。
用到的拉伸圖片的方法
- (UIImage*)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight
//可拉伸的范圍都是距離leftCapWidth后的1豎排像素微饥,和距離topCapHeight后的1橫排像素
先初始化一個imageView
UIImageView*imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame))];
第一步 拉伸圖片左邊
UIImage*image = [UIImageimageNamed:@"xxx"];
// 因為是距離leftCapWidth后的1豎排像素,所以可以把leftCapWidth設(shè)置為0
// 菱形的高度為10px古戴,所以我們要在菱形下面拉伸這個圖片欠橘。
image = [image stretchableImageWithLeftCapWidth:0 topCapHeight:5]
這樣拉伸完以后 圖片會變成-------------- ◇ - 這個樣子
第二步 改變圖片的size
// 獲取imageView的寬度
CGFloat iamgeViewWidth = CGRectGetWidth(iamgeView.frame);
// 這里imageWidth是切圖的寬度
CGFloat imageWidth = 20;
// 圖片的高度
CGFloat imageHeight = CGRectGetHeight(iamgeView.frame);
// 如果需要菱形居中顯示的話现恼,改變完以后的圖片的寬度應該是imageView寬度的1/2加上原圖寬度的1/2,這樣拉伸右邊的話肃续,菱形永遠居中
CGFloat tempWidth = (iamgeViewWidth + imageWidth) / 2.0f;
// 重新繪制Image
UIGraphicsBeginImageContextWithOptions(CGSizeMake(tempWidth,imageHeight),NO, [UIScreenmainScreen].scale);
[image drawInRect:CGRectMake(0,0, tempWidth,imageHeight)];
UIImage * newImage =UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();?
第三部 拉伸圖片右邊
// leftCapWidth設(shè)置為新圖的寬度減去1px,就會新圖拉伸最右邊的1px的圖片填充整個imageView
iamgeView.image= [newImage stretchableImageWithLeftCapWidth:tempWidth -0.5 topCapHeight:5];
這是我暫時想到的拉伸兩邊中間不變的辦法叉袍,如果哪位朋友有更好的辦法始锚,歡迎留言或者私信。