iOS开发--图片处理

时间:2023-03-08 20:04:58

  纵观现实社会和移动app市场,这是一个看脸的时代,而好看且漂亮的APP界面就是移动APP的脸.漂亮的外观后面少不了UI设计人员的辛苦,如果不懂的处理,就浪费了UI设计人员的心血.

  比如下面这张图片,是用来做按钮图片的

  iOS开发--图片处理    大小为:59 * 32

  先在把它作为一张图片显示出来,图片显示位置设置为200 * 50

  #import "ViewController.h"

   @interface ViewController ()

   @end

   @implementation ViewController

   - (void)viewDidLoad {
[super viewDidLoad];
// 对图片的拉伸
[self stretchPhoto];
} - (void)stretchPhoto
{
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(, , , )];
imageView.image = [UIImage imageNamed:@"btnbg_blue.png"];
[self.view addSubview:imageView];
} @end

  其显示效果如下:

iOS开发--图片处理

  我们可以清晰的看到,图片失去了原来的样子,尤其是四个角,这是因为图片本身大小为:59 * 32,而设置的图片显示位置的大小为200 * 50 ,图片被拉坏了.

  下面我们对这张图片设置一个拉伸点:

 #import "ViewController.h"

 @interface ViewController ()

 @end

 @implementation ViewController

 - (void)viewDidLoad {
[super viewDidLoad]; // 对图片的拉伸
[self stretchPhoto];
} // 对图片的拉伸
- (void)stretchPhoto
{
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(, , , )];
[self.view addSubview:imageView]; // 设置图片的拉伸点
UIImage *images = [UIImage imageNamed:@"btnbg_blue.png"]; // 59 * 32
images = [images stretchableImageWithLeftCapWidth: topCapHeight:];
imageView.image = images;
} @end

  其显示效果如下:

iOS开发--图片处理

  可以清楚的看到图片被完美的拉伸显示了.

  下面对设置图片拉伸点的方法做一个详解:

 - (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight;
@property(nonatomic,readonly) NSInteger leftCapWidth; // default is 0. if non-zero, horiz. stretchable. right cap is calculated as width - leftCapWidth - 1
@property(nonatomic,readonly) NSInteger topCapHeight; // default is 0. if non-zero, vert. stretchable. bottom cap is calculated as height - topCapWidth - 1

  上面的内容是Xcode文档中对该方法的解释

  第1行是方法名,返回值为UIImage对象,需要传递两个NSInteger类型的参数;

  第2行和第3行是第1行需要传递参数的两个属性,默认都是0;从其他地方看到这两个属性由一个名字叫:端盖,即左端盖宽和顶端盖高.

  这样看来,拉伸图片的话,左侧和顶部都拉伸了,那么右侧和底部呢?

  API文档给出了计算公式:rightCapWidth = image.size.width - (image.leftCapWidth + 1);       即:右端盖宽 = 图片宽 - (左端盖宽 + 1);

               bottomCapHeight = image.size.height - (image.topCapHeight + 1);  即:底部端盖 = 图片高 - (顶部端盖 + 1);

  如下图所示:

iOS开发--图片处理   

  这样可以看出,最后被拉伸的位置就是给定左端盖和顶部端盖交叉位置旁边 1 * 1 的区域(中间黄色区域),即这种方式只拉伸给定区域的 1 * 1 个点.

  一般来说,习惯给定图片宽和高一半的位置,这样可以避免不清楚边缘变化引起的不必要的麻烦.