ios图片的拉伸

时间:2023-03-09 04:04:10
ios图片的拉伸

ios图片的拉伸
  1. - (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight;
  1. // width为图片宽度
  2. rightCapWidth = width - leftCapWidth - 1;
  3. // height为图片高度
  4. bottomCapHeight = height - topCapHeight - 1

经过计算,你会发现中间的可拉伸区域只有1x1

[java] view plain copy
  1. // stretchWidth为中间可拉伸区域的宽度
  2. stretchWidth = width - leftCapWidth - rightCapWidth = 1;
  3. // stretchHeight为中间可拉伸区域的高度
  4. stretchHeight = height - topCapHeight - bottomCapHeight = 1;

因此,使用这个方法只会拉伸图片中间1x1的区域,并不会影响到边缘和角落。

下面演示下方法的使用:

[java] view plain copy
  1. // 左端盖宽度
  2. NSInteger leftCapWidth = image.size.width * 0.5f;
  3. // 顶端盖高度
  4. NSInteger topCapHeight = image.size.height * 0.5f;
  5. // 重新赋值
  6. image = [image stretchableImageWithLeftCapWidth:leftCapWidth topCapHeight:topCapHeight];
  1. - (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets
  1. CGFloat top = 25; // 顶端盖高度
  2. CGFloat bottom = 25 ; // 底端盖高度
  3. CGFloat left = 10; // 左端盖宽度
  4. CGFloat right = 10; // 右端盖宽度
  5. UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
  6. // 伸缩后重新赋值
  7. image = [image resizableImageWithCapInsets:insets];

三、iOS 6.0

在iOS6.0中,UIImage又提供了一个方法处理图片拉伸

[java] view plain copy
  1. - (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode

对比iOS5.0中的方法,只多了一个UIImageResizingMode参数,用来指定拉伸的模式:

  • UIImageResizingModeStretch:拉伸模式,通过拉伸UIEdgeInsets指定的矩形区域来填充图片
  • UIImageResizingModeTile:平铺模式,通过重复显示UIEdgeInsets指定的矩形区域来填充图片
ios图片的拉伸
可以拿到图片直接在xcode右侧设置,会自动计算保护区域