background image

iOS 

图像处理&UIImage 详解 

简介

:聊天中要实现一个个气泡这种聊天纪录效果,气泡的大小根据文本内容自动调节。刚

开始想法是将

“气泡”这张背景图片切成多张帖,4 个角、4 条边线固定到一个 container View

上,根据文本长宽不一样,改变

container View 的 frame,然后 4 个角固定,只是 4 条边线

根据

container View 在自动缩放。这样步骤很繁琐、每一个的视图坐标要反复修正。

--其实 iOS 中对图像的处理提供了相关借口,就是 UIImage 类中
stretchableImageWithLeftCapWidth: topCapHeight 方法。
--函数说明:
1.函数作用:创建一个内容可拉伸,而
边角不拉伸的图片;
2. 参 数 含 义 : The  leftCapWidth  is  the  margin  on  the  left  side  of  the  image  that  will  not  be 
stretched.If  we  set  the  leftCapWidth  to  10,  that  means  the  first  10  pixels  will  not  be  stretched. 
What will be stretched is the next single pixel. Only that pixel and nothing more, and it’s always 
just one pixel. Finally, everything to the right of that single pixel will not be stretched.  就是说
leftCapWidth 这个值是不被拉伸的像素,它的下一个像素被拉伸,之后剩下的像素不拉伸 ,

“rightCapWidth”就是 total width(原图片宽度总像素) – leftCapWidth – 1.总而言之就是

根据图片所占屏幕大小,将原图分为三部分,第一部分为

leftCapWidth 部分,不拉伸;第

二 部 分 为

“ 下 一 像 素 ” 拉 伸 ; 第 三 部 分 为 剩 下 的 “ rightCapWidth” 部 分 , 不 拉 伸 .  参 数

topCapHeight 原理类似.
3.备注:leftCapWidth/topCapHeight 这些值不一定就是图片宽度/高度的 1/2 像素左右,根据
实际情况确定。例如上面图片聊天气泡,如果

topCapHeight 值设置为图片高度的 1/2 像素,

“下一像素”刚好落在尖角斜边上,如何气泡被拉的很长,气泡右边的边下面看起来就是折
进去一点。