7

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

4

2 回答 2

22

首先,这是不推荐使用的,取而代之的是更强大的resizableImageWithCapInsets:. 但是,这仅受 iOS 5.0 及更高版本支持。

stretchableImageWithLeftCapWidth:topCapHeight:不会调整您调用它的图像的大小。它返回一个新的 UIImage。所有 UIImage 都可以以不同的大小绘制,但是一个加盖的图像通过在角落绘制它的大写来响应调整大小,然后填充剩余的空间。

这什么时候有用?当我们想用图像制作按钮时,如本教程中的 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];
}

输出:

带有和不带大写字母的 Wikimedia Commons 徽标

于 2012-04-14T02:41:52.050 回答
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];
    }
}

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

于 2012-07-03T13:05:37.900 回答