当前位置: 移动技术网 > 移动技术>移动开发>IOS > iOS图片拉伸的方法

iOS图片拉伸的方法

2019年07月24日  | 移动技术网移动技术  | 我要评论

假如下面的一张图片,是用来做按钮的背景图片的,原始尺寸是76 × 40

我们通过代码将这张图片设置为按钮的背景图片,假如我们将创建好的按钮的宽高设置为:(w=200, h=50)代码如下:

 // 初始化按钮
 uibutton *button = [[uibutton alloc] init];
 // 设置尺寸
 button.frame = cgrectmake(100, 200, 200, 50);
 
 // 加载图片
 uiimage *image = [uiimage imagenamed:@"ppm_new_shuliang.png"];
 
 // 设置背景图片
 [button setbackgroundimage:image forstate:uicontrolstatenormal];
 
 // 添加按钮 
 [self.view addsubview:button];

 结果如下:图片被拉伸了。

原因分析:是将原是尺寸为76 × 40 的图片拉伸成了w=200, h=50;

解决方案:

1.找美工重做一张较大的图片,这样的话就会出现软件包将来会变大,占用空间更大;如果我们要经常修改按钮的frame,美工设计比较繁琐;
2.苹果为我们提供了关于图片拉伸的api,我们可以直接利用代码实现;

修改后:

 // 初始化按钮
 uibutton *button = [[uibutton alloc] init];
 // 设置尺寸
 button.frame = cgrectmake(100, 200, 200, 50);
 
 cgfloat top = 0; // 顶端盖高度
 cgfloat bottom = 0 ; // 底端盖高度
 cgfloat left = 22; // 左端盖宽度
 cgfloat right = 22; // 右端盖宽度
 uiedgeinsets insets = uiedgeinsetsmake(top, left, bottom, right);
 
 
 // 加载图片
 uiimage *image = [uiimage imagenamed:@"ppm_new_shuliang.png"];
 
 image = [image resizableimagewithcapinsets:insets resizingmode:uiimageresizingmodestretch];
 
 // 设置背景图片
 [button setbackgroundimage:image forstate:uicontrolstatenormal];
 
 // 添加按钮 
 [self.view addsubview:button];


还有一种设置方法:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网