您的位置:首页 > 产品设计 > UI/UE

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

2015-08-28 14:03 591 查看
[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来填充。



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

[java] view
plaincopy

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

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

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

[java] view
plaincopy

CGFloat top = 25; // 顶端盖高度

CGFloat bottom = 25 ; // 底端盖高度

CGFloat left = 10; // 左端盖宽度

CGFloat right = 10; // 右端盖宽度

UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);

// 指定为拉伸模式,伸缩后重新赋值

image = [image resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];

运行效果:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: