背景图片的拉伸

    // 1.1 创建UIImage对象
    UIImage *image = [UIImage imageNamed:@"buttongreen"];
    
    // 1.2 拿到image的尺寸
    CGFloat imageWidth = image.size.width;
    CGFloat imageHeight = image.size.height;
    
    // 1.3 返回一张受保护而且拉伸的图片--->CapInsets:哪些地方要保护
    // 方式一:
    (1)UIImage *resizableImage = [image resizableImageWithCapInsets:UIEdgeInsetsMake(imageHeight * 0.5, imageWidth * 0.5, imageHeight * 0.5 - 1, imageWidth * 0.5 - 1)];
     /*
     UIImageResizingModeTile,  平铺
     UIImageResizingModeStretch,  拉伸(伸缩)
     */
    (2)UIImage *resizableImage = [image resizableImageWithCapInsets:UIEdgeInsetsMake(imageHeight * 0.5, imageWidth * 0.5, imageHeight * 0.5 - 1, imageWidth * 0.5 - 1) resizingMode:UIImageResizingModeTile];

    // 方式二:
       // 右边需要被保护的区域 = 图片的width - leftCapWidth - 1
       // 底部需要被保护的区域(bottom cap) = height - topCapHeight - 1
    UIImage *resizableImage = [image stretchableImageWithLeftCapWidth:imageWidth * 0.5 topCapHeight:imageHeight * 0.5];

    // 2.把图片设置到按钮上
    [self.button setBackgroundImage:resizableImage forState:UIControlStateNormal];
由于可能在项目中很多地方要用到图片拉伸方法,所以把它定义成为一个类扩展
#import <UIKit/UIKit.h>
@interface UIImage (SJMExtention)
/**
 *  返回一张受保护的图片(被拉伸的)
 */
+ (instancetype)resizableImageWithLocalImageName:(NSString *)localImageName;
@end

#import "UIImage+SJMExtention.h"
@implementation UIImage (SJMExtention)

+ (instancetype)resizableImageWithLocalImageName:(NSString *)localImageName {
    // 创建图片对象
    UIImage *image = [UIImage imageNamed:localImageName];
    
    // 获取图片的尺寸
    CGFloat imageWidth = image.size.width;
    CGFloat imageHeight = image.size.height;
    
    return [image stretchableImageWithLeftCapWidth:imageWidth * 0.5 topCapHeight:imageHeight * 0.5];
}
@end

不用代码设置: 选中图片,选择水平和垂直拉伸,修改受保护的区域(宽/2, 高/2)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 如果不采用相应技术对button的背景图片进行拉伸,则显示的效果就会失真,效果: iOS中有三种方法对图片进行拉伸...
    冷洪林阅读 9,662评论 0 4
  • 给view用shape或者layerlist层叠背景时,经常遇到背景拉伸,不是预期的效果。今天发现如下方法可以很完...
    浩运阅读 9,824评论 0 4
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,270评论 25 709
  • 荃国有一个朝代名曰蕤,蕤朝的人口只有七口,四口曰女,三口曰男,可是蕤朝的国土面积却大到离谱,自然资源也多得令人乍舌...
    AnasFeng阅读 1,709评论 1 0
  • 你们知道吗,每天都有几十万的上班族天天奔波在燕郊和北京之间,两地相距最低五十多公里,多则上百公里,每天穿梭在这两座...
    梦洒幽幽阅读 1,469评论 0 0