iOS 图片拉伸的三种方法

作者: 一个很帅的蓝孩子 | 来源:发表于2017-02-15 10:30 被阅读0次

1、直接拉伸

    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 200, 100)];
    UIImage *image = [UIImage imageNamed:@"123"];
    image = [image stretchableImageWithLeftCapWidth:image.size.width * 0.5 topCapHeight:image.size.height * 0.5];
    imageView.image = image;
    [self.view addSubview:imageView];
直接拉伸.png

stretchable可拉伸的,要传两个参数

// default is 0. if non-zero, horiz. stretchable. right cap is calculated as width - leftCapWidth - 1
// default is 0. if non-zero, vert. stretchable. bottom cap is calculated as height - topCapWidth - 1

默认为0,是整个直接拉伸的,所以直接设置可能会发生形变或者模糊很丑,第一个参数是设置左边不被拉伸的尺寸,我们默认设置为宽度的一半,右边会自动设置为:Image.size.width - leftCapWidth - 1,所以中间可拉伸的尺寸为1,同理topCapHeight也是一样,所以中间可被拉伸的frame为1 x 1。

原图123.png
拉伸之后的图片.png
不拉伸直接设置发生形变的图片.png

2、设置不被拉伸的区域

    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 200, 100)];
    UIImage *image = [UIImage imageNamed:@"123"];
    image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(image.size.height * 0.5 -1, image.size.width * 0.5 -1, image.size.height * 0.5 -1, image.size.width * 0.5 -1) resizingMode:UIImageResizingModeStretch];
    imageView.image = image;
    [self.view addSubview:imageView];

CapInsets这里设置的为不被拉伸的区域,如果上下设置为高度的一半 - 1,左右设置为宽度一半 - 1,则拉伸区域为 2 x 2,当然上下直接设置为高度一半,左右设置为宽度一半也是有效;resizingMode为显示的模式:UIImageResizingModeTile为平铺模式,UIImageResizingModeStretch为拉伸模式。

3、直接在Assets.xcassets里设置

在Assets.xcassets中选中该图片,右边有一个slicing的属性,选择Horizontal and Vertical ,center选中Stretches,width和height默认为1 x 1

屏幕快照 2017-02-15 10.20.25.png 屏幕快照 2017-02-15 10.27.04.png

相关文章

网友评论

    本文标题:iOS 图片拉伸的三种方法

    本文链接:https://www.haomeiwen.com/subject/ntafwttx.html