使用 resizableImageWithCapInsets 方法实现可伸缩图片

之前介绍过通过 stretchableImageWithLeftCapWidth:topCapHeight: 方法来实现可伸缩图片;

可看这篇随笔:使用 stretchableImageWithLeftCapWidth 方法实现可伸缩图片

 

iOS5 中提供了一个新的 UIImage 对象实例方法:resizableImageWithCapInsets:,可以将图片转换为以某一偏移值为偏移的可伸缩图片(偏移值内的图片内容将不被拉伸或压缩)。

stretchableImageWithLeftCapWidth:topCapHeight: 模式(此方法已经过期,推荐用下面的resizableImageWithCapInsets: 方法);

resizableImageWithCapInsets: 模式还能实现类似图片渐变的效果,更灵活控制。

 

效果如下:

ViewController.h

1 #import <UIKit/UIKit.h>
2 
3 @interface ViewController : UIViewController
4 @end

ViewController.m

 1 #import "ViewController.h"
 2 
 3 @interface ViewController ()
 4 - (void)layoutUI;
 5 @end
 6 
 7 @implementation ViewController
 8 #define kWidthOfButton 160.0
 9 #define kHeightOfButton 49.0
10 
11 - (void)viewDidLoad {
12     [super viewDidLoad];
13     
14     [self layoutUI];
15 }
16 
17 - (void)didReceiveMemoryWarning {
18     [super didReceiveMemoryWarning];
19     // Dispose of any resources that can be recreated.
20 }
21 
22 - (void)layoutUI {
23     //普通模式
24     UIImage *img = [UIImage imageNamed:@"blueButton"]; //size: 39*39
25     UIButton *btnNormal = [[UIButton alloc] initWithFrame:CGRectMake(20.0, 40.0, kWidthOfButton, kHeightOfButton)];
26     [btnNormal setTitle:@"btnNormal" forState:UIControlStateNormal];
27     [btnNormal setBackgroundImage:img forState:UIControlStateNormal];
28     [self.view addSubview:btnNormal];
29     
30     //stretchableImageWithLeftCapWidth:topCapHeight:模式(此方法已经过期,推荐用下面的resizableImageWithCapInsets:方法)
31     UIImage *imgStretchable = [img stretchableImageWithLeftCapWidth:16.0 topCapHeight:16.0];
32     UIButton *btnStretchable = [[UIButton alloc] initWithFrame:CGRectMake(20.0, 50.0+kHeightOfButton, kWidthOfButton, kHeightOfButton)];
33     [btnStretchable setTitle:@"btnStretchable" forState:UIControlStateNormal];
34     [btnStretchable setBackgroundImage:imgStretchable forState:UIControlStateNormal];
35     [self.view addSubview:btnStretchable];
36     
37     //resizableImageWithCapInsets:模式;相比stretchableImageWithLeftCapWidth:topCapHeight:模式来说,resizableImageWithCapInsets:模式还能实现类似图片渐变的效果,更灵活控制
38     UIImage *imgResizable = [img resizableImageWithCapInsets:UIEdgeInsetsMake(30.0, 16.0, 9.0, 16.0)];
39     UIButton *btnResizable = [[UIButton alloc] initWithFrame:CGRectMake(20.0, 60.0+(kHeightOfButton*2), kWidthOfButton, kHeightOfButton)];
40     [btnResizable setTitle:@"btnResizable" forState:UIControlStateNormal];
41     [btnResizable setBackgroundImage:imgResizable forState:UIControlStateNormal];
42     [self.view addSubview:btnResizable];
43 }
44 
45 @end

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值