UIImage stretchableImageWithLeftCapWidth

Kai*_*bin 7 iphone

在iOS中,是否有任何UIImage支持stretchableImageWithLeftCapWidth :,这是否意味着自动调整uimmage?

Don*_*mer 22

首先,这是被弃用的,取而代之的是更强大的resizableImageWithCapInsets:.但是,仅iOS 5.0及更高版本支持.

stretchableImageWithLeftCapWidth:topCapHeight:不会调整您调用它的图像的大小.它返回一个新的UIImage.所有UIImages都可以以不同的尺寸绘制,但是上限图像通过在角落处绘制其大写字母来响应调整大小,然后填充剩余空间.

什么时候有用?当我们想要从图像中制作按钮时,如本教程中的iOS 5版本.

以下代码是一个UIView drawRect方法,它说明了UIImage带有大写字母的常规图像和可伸缩图像之间的区别.用于的图像stretch.png来自http://commons.wikimedia.org/wiki/Main_Page.

- (void) drawRect:(CGRect)rect;
{
    CGRect bounds = self.bounds;

    UIImage *sourceImage = [UIImage imageNamed:@"stretch.png"];
    // Cap sizes should be carefully chosen for an appropriate part of the image.
    UIImage *cappedImage = [sourceImage stretchableImageWithLeftCapWidth:64 topCapHeight:71];

    CGRect leftHalf = CGRectMake(bounds.origin.x, bounds.origin.y, bounds.size.width/2, bounds.size.height);
    CGRect rightHalf = CGRectMake(bounds.origin.x+bounds.size.width/2, bounds.origin.y, bounds.size.width/2, bounds.size.height);
    [sourceImage drawInRect:leftHalf];
    [cappedImage drawInRect:rightHalf];

    UIFont *font = [UIFont systemFontOfSize:[UIFont systemFontSize]];
    [@"Stretching a standard UIImage" drawInRect:leftHalf withFont:font];
    [@"Stretching a capped UIImage" drawInRect:rightHalf withFont:font];
}
Run Code Online (Sandbox Code Playgroud)

输出:

维基媒体公共徽标,有或没有帽子


And*_*obs 13

我写了一个类别方法来保持兼容性

- (UIImage *) resizableImageWithSize:(CGSize)size
{
    if( [self respondsToSelector:@selector(resizableImageWithCapInsets:)] )
    {
        return [self resizableImageWithCapInsets:UIEdgeInsetsMake(size.height, size.width, size.height, size.width)];
    } else {
        return [self stretchableImageWithLeftCapWidth:size.width topCapHeight:size.height];
    }
}
Run Code Online (Sandbox Code Playgroud)

只需将它放入你已经拥有的UIImage类别(或者创建一个新的),这只支持旧方式可伸缩的大小调整,如果你需要更复杂的可伸缩图像大小调整你只能在iOS 5上使用resizableImageWithCapInsets:直接