iOS图片拉伸的4种方法

2020-01-18 20:05:08王冬梅

假如下面的一张图片,是用来做按钮的背景图片的,原始尺寸是(128 * 112)

iOS,图片拉伸

按钮背景图片.png

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


//
// ViewController.m
// iOS图片拉伸总结
//
// Created by Sunshine on 15/6/29.
// Copyright (c) 2015年 YotrolZ. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
 [super viewDidLoad];

 // 创建一个按钮
 UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];

 // 设置按钮的frame
 btn.frame = CGRectMake(100, 300, 200, 50);

 // 加载图片
 UIImage *image = [UIImage imageNamed:@"chat_send_nor"];

 // 设置按钮的背景图片
 [btn setBackgroundImage:image forState:UIControlStateNormal];

 // 将按钮添加到控制器的view
 [self.view addSubview:btn];

}

- (void)didReceiveMemoryWarning {
 [super didReceiveMemoryWarning];
 // Dispose of any resources that can be recreated.
}

@end

这是你发现运行的结果完全出乎你的意料(搓的无极限),如图:

iOS,图片拉伸

运行效果图1.png

原因分析:是将原是尺寸为W=128 * H=112的图片拉伸成了W=200, H=50;

解决方案:
1.找美工MM重做一张较大的图片,这样的话就会出现软件包将来会变大,占用空间更大;如果我们要经常修改按钮的frame,你是想让MM杀你的节奏~~,显然不可行;
2.苹果为我们提供了关于图片拉伸的API,我们可以直接利用代码实现,是不是很牛X;

利用苹果提供的API来拉伸图片(目前发现的有四种):

方式一(iOS5之前):

如下图:设置topCapHeight、leftCapWidth、bottomCapHeight、lerightCapWidth,图中的黑色区域就是图片拉伸的范围,也就是说边上的不会被拉伸.
通过下面的方法我们可以设置:

// 官方API说明
// - stretchableImageWithLeftCapWidth:topCapHeight:(iOS 5.0)
// Creates and returns a new image object with the specified cap values.

说明:这个方法只有2个参数,leftCapWidth代表左端盖宽度,topCapHeight代表上端盖高度。系统会自动计算出右端盖宽度rightCapWidth和底端盖高度bottomCapHeight,算法如下:


// 系统会自动计算rightCapWidth
rightCapWidth = image.width - leftCapWidth - 1; 

// 系统会自动计算bottomCapHeight
bottomCapHeight = image.height - topCapHeight - 1