源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

iOS图片拉伸的方法

  • 时间:2020-08-04 15:45 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:iOS图片拉伸的方法
假如下面的一张图片,是用来做按钮的背景图片的,原始尺寸是76 × 40 [img]http://files.jb51.net/file_images/article/201701/201711790208223.jpg?20170179233[/img] 我们通过代码将这张图片设置为按钮的背景图片,假如我们将创建好的按钮的宽高设置为:(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];
 结果如下:图片被拉伸了。 [img]http://files.jb51.net/file_images/article/201701/201701170859492.png[/img] 原因分析:是将原是尺寸为76 × 40 的图片拉伸成了W=200, H=50; [b]解决方案: [/b]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];


[img]http://files.jb51.net/file_images/article/201701/201701170859493.png[/img] 还有一种设置方法: [img]http://files.jb51.net/file_images/article/201701/201701170859494.png[/img] [img]http://files.jb51.net/file_images/article/201701/201701170859495.png[/img] 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部