图片拉伸 [UIImage resizableImageWithCapInsets:]使用注意

[UIImage resizableImageWithCapInsets:]

它带参数: UIEdgeInsets,这是一结构体,包含 上/左/下/右四个参数。函数的作用我们看下文档:

Creates and returns a new image object with the specified cap insets.

Discussion

You use this method to add cap insets to an image or to change the existing cap insets of an image. In both cases, you get back a new image and the original image remains untouched.

During scaling or resizing of the image, areas covered by a cap are not scaled or resized. Instead, the pixel area not covered by the cap in each direction is tiled, left-to-right and top-to-bottom, to resize the image. This technique is often used to create variable-width buttons, which retain the same rounded corners but whose center region grows or shrinks as needed. For best performance, use a tiled area that is a 1×1 pixel area in size.

上左下右4参数定义了cap inset,就是离四条边的距离。拉升时,cap到边的部分不会被拉升,其余部分则会被拉升。尤其需要注意的时,拉升的时候,是从左到右,从上到下的方向。通俗点说,拉升不是全方向的拉升,而是垂直和水平拉升的叠加。


- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    UIImage *img = [UIImageimageNamed:@"ldialog"];

    img = [img resizableImageWithCapInsets:UIEdgeInsetsMake(30,3030,30)resizingMode:UIImageResizingModeTile];

    UIImageView *imgview = [[UIImageViewalloc]initWithImage:img];

    [self.viewaddSubview:imgview];

    imgview.frame=CGRectMake(0,50160,60);

    

}



说白了就是设置图片上下左右四个边的内容保持不变,中间和四个侧边进行拉伸

然后根据外面的容器(imgview)的frame来填充,按照中间那块来填充

这里有个角,要设置的上左够大才能保持不被拉伸到,上几个图,其中有一个就是上左设置的太小拉伸到

  img = [img resizableImageWithCapInsets:UIEdgeInsetsMake(10,1030,30)resizingMode:UIImageResizingModeTile];

足够大的设置

  img = [img resizableImageWithCapInsets:UIEdgeInsetsMake(30, 30,30,30)resizingMode:UIImageResizingModeTile];

这些都是设置imgview的frame来填充。

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

[java]  view plain copy

  1. - (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode  

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

  • UIImageResizingModeStretch:拉伸模式,通过拉伸UIEdgeInsets指定的矩形区域来填充图片
  • UIImageResizingModeTile:平铺模式,通过重复显示UIEdgeInsets指定的矩形区域来填充图片

[java]  view plain copy

  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 resizingMode:UIImageResizingModeStretch];  

运行效果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值