效果图,上面是原始图片,下面是拉伸过的图。

朋友问我的,一开始我以为很简单,我就开始尝试写了:
- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode;
一开始用这个方法,不行,箭头总在一边
- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight
后来用这个,也不行,还是在一边

接着用了Show Slicing,也不行,箭头还是在一边,或者出现一些奇怪的图片,不是想要的效果。
最后还是要依靠我大网友,在 聊天气泡图片对称拉伸(箭头保持在中间) 得到了解决方法。
思路如下:

对小图片箭头右侧进行拉伸,拉伸后生成一张图片,再对这个图片进行左侧拉伸,保证两侧拉伸的距离一样就可以了。
//初始图片
UIImage *initialImage = [UIImage imageNamed:@"jiantou"];
//拉伸图片右侧
UIImage *rightStretchImage = [initialImage stretchableImageWithLeftCapWidth:initialImage.size.width *0.8 topCapHeight:initialImage.size.height *0.5];
//拉伸后的宽度=总宽度/2+初始图片宽度/2
CGFloat stretchWidth = (SCREEN_WIDTH-60)/2+initialImage.size.width/2;
//获得右侧拉伸过后的图片
UIGraphicsBeginImageContextWithOptions(CGSizeMake(stretchWidth, 90), NO, [UIScreen mainScreen].scale);
[rightStretchImage drawInRect:CGRectMake(0, 0, stretchWidth, 90)];
UIImage *firstStretchImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//拉伸图片左侧,获得最终图片
UIImage *finalImage = [firstStretchImage stretchableImageWithLeftCapWidth:initialImage.size.width *0.2 topCapHeight:initialImage.size.height*0.5];
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(30, 200, SCREEN_WIDTH-60, 100)];
imageView.image = finalImage;
[self.view addSubview:imageView];
GitHub:StretchImage
网友评论