在我们开发过程中,经常会用到图片的拉伸,比如做聊天消息气泡的处理,如下:
原图:
原图.png
用系统默认拉伸后的图片:
默认拉伸效果图.png
//这是因为将16 * 16的图拉成了350 * 80的图
UIImageView *img = [[UIImageView alloc] init];
img.center = CGPointMake(self.view.frame.size.width * 0.5, self.view.frame.size.height * 0.5);
img.bounds = CGRectMake(0, 0, 350, 80);
img.image = [UIImage imageNamed:@"qipao"];
[self.view addSubview:img];
这样的图片不仅失真而且变形达不到我们想要的效果,那么如何达到我们想要的效果呢,请看一下几种方式:
1、方式一
效果图.png
实现代码:
UIImageView *img = [[UIImageView alloc] init];
img.center = CGPointMake(self.view.frame.size.width * 0.5, self.view.frame.size.height * 0.5);
img.bounds = CGRectMake(0, 0, 350, 80);
UIImage *image = [UIImage imageNamed:@"qipao"];
UIImage *newImage = [image stretchableImageWithLeftCapWidth:image.size.width * 0.5 topCapHeight:image.size.height * 0.5];
img.image = newImage;
[self.view addSubview:img];
这里主要是设置leftCapWidth和topCapHeight,它会自动计算rightCapWidth和bottomCapHeight
rightCapWidth = image.width - leftCapWidth - 1;
bottomCapHeight = image.height - topCapHeight - 1;
最终拉伸的区域也就是1*1,总体下来不会影响拉伸效果
2、方式二(小鹿哥推荐使用)
实现代码:
UIImageView *img = [[UIImageView alloc] init];
img.center = CGPointMake(self.view.frame.size.width * 0.5, self.view.frame.size.height * 0.5);
img.bounds = CGRectMake(0, 0, 350, 80);
UIImage *image = [UIImage imageNamed:@"qipao"];
UIImage *newImage = [image resizableImageWithCapInsets:UIEdgeInsetsMake(image.size.height * 0.5, image.size.width * 0.5, image.size.height * 0.5, image.size.height * 0.5) resizingMode:UIImageResizingModeStretch];
img.image = newImage;
[self.view addSubview:img];
3、方式三
直接在Asset对图片设置
设置步骤:
1、
ShowSlicing.png
2、
StartSlicing.png
3、
选中图片区域.png
4、
进行设置.png
网友评论