[UIImage resizableImageWithCapInsets:]使用注意

本文介绍了如何使用 UIKit 中的 resizableImageWithCapInsets 方法来创建可拉伸的图片。通过设置图片的 cap insets,可以确保图片的特定区域(如圆角按钮的边框)在拉伸过程中保持不变,而其他部分则进行拉伸以适应不同的尺寸。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[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,30, 30,30) resizingMode:UIImageResizingModeTile];

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

    [self.viewaddSubview:imgview];

    imgview.frame=CGRectMake(0,50, 160,60);

    

}



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

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

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

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

足够大的设置

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

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值