UIImage resizableImageWithCapInsets的方法讲解[转载]

最近在sae上搭建了个wp,因为深感自己前端的东西缺乏,所以想依次为契机,学习一下。本文是从个人的sae版wp转载过来。

本篇也是在实现微博过程中遇到的问题。原先以为很简单的东西,到了实际做的时候,才发现这里出错那里不对。浪费很多时间,究根结底,还是没有弄清楚文档。

在iOS5, UIImage添加了可以拉伸图片的函数,即:

[UIImage resizableImageWithCapInsets:]

它带参数: UIEdgeInsets,这是一结构体,包含 上/左/下/右四个参数。函数的作用我们看下文档:

Creates and returns a new image object with the specified cap insets.

Discussion

You use this method to add cap insets to an image or to change the existing cap insets of an image. In both cases, you get back a new image and the original image remains untouched.

During scaling or resizing of the image, areas covered by a cap are not scaled or resized. Instead, the pixel area not covered by the cap in each direction is tiled, left-to-right and top-to-bottom, to resize the image. This technique is often used to create variable-width buttons, which retain the same rounded corners but whose center region grows or shrinks as needed. For best performance, use a tiled area that is a 1×1 pixel area in size.

上左下右4参数定义了cap inset,就是离四条边的距离。拉升时,cap到边的部分不会被拉升,其余部分则会被拉升。尤其需要注意的时,拉升的时候,是从左到右,从上到下的方向。通俗点说,拉升不是全方向的拉升,而是垂直和水平拉升的叠加。

以我遇到的问题为例,我的图片是170×50, 需要填充到240×140,但是四周的圆角以及小箭头保持原样,如图:

popover_background_left

开始我设置参数{20,10,10,10},在图上的位置大致:

imageWrong

这样拉升的结果:

屏幕快照 2013-09-04 10.31.48 PM

很奇怪是不是,为什么出现了两个箭头(红色部分是设置的背景色用语区分)?再回头看下文档,才恍然大悟:

  1. 拉升的时候,是按前文说的两个方向来拉升
  2. 拉升的部分,是以tiled方式,简单的说就是以镜像的方式

按照1的规则,拉升的时候,水平和垂直方向都需要拉升。这样在水平拉升的时候,箭头其实处于拉升的部分。而拉升的时候,先按照原有的尺寸添加进去,不足的地方再把中间不拉升的部分填充进去,周而复始,直到填充完毕。因此,就有上面的现象了。

要达到需要的效果,必须按照如下的设置:

imageRight

于是得到了我们需要的效果:

屏幕快照 2013-09-04 10.39.10 PM

Binggo~ 一切完毕。

同样,如果这些内容还是不能满足您的需求,您可以参考以下链接:

http://www.cnblogs.com/zhangqifeng/p/4004433.html

http://blog.sina.com.cn/s/blog_884e78b2010150b3.html

http://duchengjiu.iteye.com/blog/1901288

 
 
原文地址:https://www.cnblogs.com/gepf/p/4913200.html