iOS:如何通过UIEdgeInsetsMake来制作可伸缩的Button

来源:互联网 发布:ubuntu mate中文设置 编辑:程序博客网 时间:2024/05/22 16:39

注:本文翻译自国外iOS开发者Natasha The Robot的一篇博文,链接在此。
在iOS应用中,经常会有很多Button有相同的背景图片,却由于处在不同的位置而大小不同(尽管在iOS7中Button已经没有背景图片了)。比如,一个功能为“Save”的Button要比功能为“Submit”要窄一些,但是他们都可以拥有紫色背景。
在这篇文章中,你不需要为每个button准备不同的背景图片。你很幸运,因为iOS的UIEdgeInsetsMake方法可以很方便的把这张图片: 


变成这张:


解决办法很简单:较小的图片的四个圆角保持不变,中间部分可以在竖直与水平方向上复制,这样,图片的中间部分就可以按照你的要求来放大了。
可以通过UIEdgeInsets来实现这个功能:你可以在拉伸图片时,在图片中上、左、下、右四个边缘指定出不允许拉伸的部分。UIEdgeInsets本身是一个结构体,包含四个float类型的浮点数:

typedef struct {   CGFloat top, left, bottom, right;} UIEdgeInsets;

代替全部
我新建了一个项目:在stordboard中我添加了一个自定义的Button,然后在ViewController中为其创建了一个Outlet。在我的ViewDidLoad:方法中,我调用了私有方法configureButton,它通过UIEdgeInsetsMake(0,0,0,0)来构建了一个UIEdgeInsets:
- (void)configureButton{    UIEdgeInsets edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);    UIImage *backgroundButtonImage = [[UIImage imageNamed:@"purple_button.png"]                                      resizableImageWithCapInsets:edgeInsets];    [self.purpleButton setBackgroundImage:backgroundButtonImage                                 forState:UIControlStateNormal];}

由于没有为指定不拉伸区域(四个方向上不允许拉伸的区域都设置为0),所以是整个图片在水平和竖直方向上复制,结果如下:


竖直限定
给图片添加竖直限定,我们需要向下面这个示意图一样忽略掉左右两个边缘:




在两条竖线间的区域可以在水平方向上复制。可以忽略掉左右两边各留8个像素的距离,将UIEdgeInsets设置为UIEdgeInsetsMake(0,8,0,8):
- (void)configureButton{    UIEdgeInsets edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);    UIImage *backgroundButtonImage = [[UIImage imageNamed:@"purple_button.png"]                                      resizableImageWithCapInsets:edgeInsets];    [self.purpleButton setBackgroundImage:backgroundButtonImage                                 forState:UIControlStateNormal];}

结果看起来好多了:




水平限定
相似的,如果你想为图片添加水平方向的限定,可以忽略掉距上下边缘各8个像素的距离,仅复制两条线之间的区域:


将UIEdgeInsets设置为UIEdgeInsetsMake(8,0,8,0):
- (void)configureButton{    UIEdgeInsets edgeInsets = UIEdgeInsetsMake(8, 0, 8, 0);    UIImage *backgroundButtonImage = [[UIImage imageNamed:@"purple_button.png"]                                      resizableImageWithCapInsets:edgeInsets];    [self.purpleButton setBackgroundImage:backgroundButtonImage                                 forState:UIControlStateNormal];}

结果如下:


在两个方向上进行限定
如果希望在水平和竖直方向上都对可以复制区域加以限定,我们需要将上、下、左、右四个边缘的内侧8个像素的区域都忽略掉:


将UIEdgeInsets设置为UIEdgeInsetsMake(8,8,8,8):
- (void)configureButton{    UIEdgeInsets edgeInsets = UIEdgeInsetsMake(8, 8, 8, 8);    UIImage *backgroundButtonImage = [[UIImage imageNamed:@"purple_button.png"]                                      resizableImageWithCapInsets:edgeInsets];    [self.purpleButton setBackgroundImage:backgroundButtonImage                                 forState:UIControlStateNormal];}

太棒了!我们现在有一个正确显示的Button了:




现在,如果你需要其他紫色的button,你只需要把刚才那个小正方形的图片的四个边忽略掉,然后将图片中间部分按照你希望的大小进行复制就可以了。Enjoy!




0 0
原创粉丝点击