IOS开发-09.图片拉伸不变形

来源:互联网 发布:rs422数据帧格式 编辑:程序博客网 时间:2024/05/16 07:38

1.概述

  • 在开发中我们经常会设置控件的背景图片,有时图片太小,而一般系统默认的图片内容显示是填充整个视图的,这个时候若是图片四角是圆角或其他不规则形状的话,在拉伸后会造成图片变形,为了解决这种情况,苹果特别提供了一些方法来保证图片在拉伸后,四角不变形
  • 图例
    这里写图片描述

2.故事板中直接设置

  • 方法1:
    • 在Xcode6之后,我们可以在资源文件中直接设置图片的属性,通过设置slicing属性,默认情况下是none,我们可以设置水平方向拉伸,垂直方向拉伸,以及水平方向和垂直方向都拉伸
      这里写图片描述
      -方法2:
    • 实现原理和方法一类似,只不过更加直观,我们可以直接选择show overView,通过拖拽直接设置可拉伸区域,更加直观
      这里写图片描述
      这里写图片描述

3.代码设置

  • 1.iOS5以前的方法实现原理(了解)
// LeftCapWidth: 左边多少不能拉伸// 右边多少不能拉伸 = 控件的宽度 - 左边多少不能拉伸 - 1//  right  =  width - leftCapWidth - 1// 1 = width - leftCapWidth - right// topCapHeight: 顶部多少不能拉伸// 底部有多少不能拉伸 = 控件的高度 - 顶部多少不能拉伸 - 1//  bottom =  height - topCapWidth - 1// 1 = height - topCapWidth - bottom// stretchableImageWithLeftCapWidth:返回一个新的图片UIImage *newImage = [image stretchableImageWithLeftCapWidth:5 topCapHeight:5];
  • 2.IOS 5实现方法(了解)
// UIEdgeInsets是告诉系统哪些地方需要受保护, 也就是不可以拉伸// resizableImageWithCapInsets默认拉伸方式是平铺UIEdgeInsets insets = UIEdgeInsetsMake(image.size.height * 0.5, image.size.width * 0.5, image.size.height * 0.5, image.size.width * 0.5);//这里设置保护区域后,会在中心点很小的一个视图进行拉伸UIImage *newImage = [image resizableImageWithCapInsets:insets];
  • 3.IOS 6以后的实现方法
UIButton *btn = [[UIButton alloc] init];UIImage *image = [UIImage imageNamed:@"图片名称"];// resizingMode指定拉伸模式// 平铺UIImageResizingModeTile// 拉伸UIImageResizingModeStretchUIEdgeInsets insets = UIEdgeInsetsMake(5, 5, 5, 5);UIImage *newImage =  [image resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];[btn setBackgroundImage:newImage forState:UIControlStateNormal];btn.frame = CGRectMake(100, 100, 200, 80);[self.view addSubview:btn];
0 0
原创粉丝点击