Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImage stretchableImageWithLeftCapWidth

Tags:

iphone

in iOS, does any UIImage support stretchableImageWithLeftCapWidth: , does that mean autoresize the uimmage?

like image 882
Kaibin Avatar asked Apr 14 '12 02:04

Kaibin


2 Answers

First, this is deprecated, replaced by the more powerful resizableImageWithCapInsets:. However, that is only supported by iOS 5.0 and above.

stretchableImageWithLeftCapWidth:topCapHeight: does not resize the image you call it on. It returns a new UIImage. All UIImages may be drawn at different sizes, but a capped image responds to resizing by drawing its caps at the corners, and then filling the remaining space.

When is this useful? When we want to make buttons out of an image, as in this tutorial for the iOS 5 version.

The following code is a UIView drawRect method which illustrates the difference between a regular UIImage and a stretchable image with caps. The image used for stretch.png came from 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];
}

Output:

Wikimedia commons logo stretched with and without caps

like image 69
Cowirrie Avatar answered Nov 16 '22 10:11

Cowirrie


I have written a category method for maintaining compatibility

- (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];
    }
}

just put that into your UIImage category you already have ( or make a new one ) this only supports the old way stretchable resizing, if you need more complex stretchable image resizing you can only do that on iOS 5 using the resizableImageWithCapInsets: directly

like image 25
Andy Jacobs Avatar answered Nov 16 '22 09:11

Andy Jacobs