UIImage Class Reference

Inherits from NSObject
Framework /System/Library/Frameworks/UIKit.framework
Availability Available in iOS 2.0 and later.

Stretch

拉伸为

代码:

UIImage *originalImage = [UIImage imageNamed:@"myImage.png"];
UIImage *newImage = nil;

if ([originalImage respondsToSelector:@selector(resizableImageWithCapInsets:)]) {
    // iOS 5 and obove.
    newImage = [originalImage resizableImageWithCapInsets:(UIEdgeInsets){15, 5, 15, 5}]
}
else {
    newImage = [originalImage stretchableImageWithLeftCapWidth:5 topCapHeight:15];
}

A stretchable image is divided into 9 parts, if both leftCapWidth and topCapHeight are nonzero.

leftCapWidth
<----->
+--------------+ ^
|     | |      | |
|  A  | |  B   | | topCapHeight
|-----+·+------| v
|-----+·+------|
|  C  | |  D   |
|     | |      |
+--------------+

The central parts are always 1 px in size, and this is the part that is stretched, for example:

leftCapWidth (constant!)
  <----->
  +------------------+ ^
  |     |     |      | |
  |  A  |     |  B   | | topCapHeight (constant!)
v |-----+ - - +------| v
| |     .     .      |
| |     .     .      |
^ |-----+ - - +------|
  |  C  |     |  D   |
  |     |     |      |
  +------------------+
        >-----<
    stretched region

To create a "glass pill button", you should fill the rounded border into the regions A, B, C and D above, and supply the radius of that pill into both the leftCapWidth and topCapHeight.

Also, a stretchable image is not shrinkable. If you try to use stretchable images bigger than the buttons (or whatever else) you want to apply it to, they may be rendered incorrectly (especially on older iOSes).

引用 Stackoverflow