天天看点

iOS 图片拉伸的多种方式

  在开发过程中我们经常会遇到一些图片像素不够,需要拉伸放大来作显示,列如聊天背景框需要跟随内容而拉伸适应,但是如果直接改变图片宽高会使得图片变得模糊。所以我们就要来想办法保护一部分图片不做拉伸,只对局部进行拉伸以确保图片不被拉伸变形。这里提供了三种拉伸方式,其原理都是设置保护区域,只对中间一个像素点进行拉伸。

效果展示

左边是直接拉伸宽高 右边是拉伸一个像素点

iOS 图片拉伸的多种方式
iOS 图片拉伸的多种方式

resizableImageWithCapInsets拉伸方式

  resizableImageWithCapInsets拉伸具有两个方法,一种是不设置拉伸模式的方法(使用默认拉伸方式),一种是设置拉伸模式的方法。

不带拉伸模式

UIImage* img = [UIImage imageNamed:@"img"];
    CGFloat imgWidth = img.size.width;
    CGFloat imgHeight = img.size.height;
    UIImage* resizableImg = [img resizableImageWithCapInsets:UIEdgeInsetsMake(imgHeight*0.5,imgWidth*0.5, imgHeight*0.5-1, imgWidth*0.5-1)];
    self.imgView.image = resizableImg;
           

带拉伸模式

  带拉伸模式的方法中拉伸模式一共有两种,当只对一个点进行拉伸时这两种模式是无法看出区别的。

  • UIImageResizingModeTile 保护区域外采用平铺的方式将区域填满。
  • UIImageResizingModeStretch 保护区域外采用拉伸的方式将区域直接进行拉伸。
UIImage* img = [UIImage imageNamed:@"img"];
    CGFloat imgWidth = img.size.width;
    CGFloat imgHeight = img.size.height;
    UIImage* resizableImg = [img resizableImageWithCapInsets:UIEdgeInsetsMake(imgHeight*0.5,imgWidth*0.5, imgHeight*0.5-1, imgWidth*0.5-1) resizingMode:UIImageResizingModeTile]; //共两种模式
    self.imgView.image = resizableImg;
           

stretchableImageWithLeftCapWidth拉伸方式

  相对于resizableImageWithCapInsets拉伸方式stretchableImageWithLeftCapWidth更简单,只需要传递两个值即可,所以开发中使用也就更多一点。

UIImage* img = [UIImage imageNamed:@"img"];
 CGFloat imgWidth = img.size.width;
 CGFloat imgHeight = img.size.height;
UIImage* resizableImg = [img stretchableImageWithLeftCapWidth:imgWidth*0.5 topCapHeight:imgHeight*0.5];
    self.imgView.image = resizableImg;
           

在Assets中设置图片属性进行拉伸

  这种方式和resizableImageWithCapInsets类似,同样是传入受保护区域的四个值,只不过我们不用通过代码来控制,只用设置相关配置即可。打开Assets资源找到需要设置的图片,然后设置其Slices值为水平和垂直,然后填入保护区域即可。

iOS 图片拉伸的多种方式