UIImage stretchableImageWithLeftCapWidth

8

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

2个回答

23

首先,这个方法已被弃用,取而代之的是更加强大的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 logo stretched with and without caps


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:


这段代码应该进行小修改以防止下一个问题:https://dev59.com/q2oy5IYBdhLWcg3wQr1i#8673145 - Maxim Kholyavkin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接