UIImage stretchableImageWithLeftCapWidth

in iOS, any UIImage support stretchableImageWithLeftCapWidth :, does that mean auto-resisting uimmage?

+7
source share
2 answers

Firstly, it is deprecated, replaced by the more powerful resizableImageWithCapInsets: However, this is only supported on iOS 5.0 and higher.

stretchableImageWithLeftCapWidth:topCapHeight: does not resize the image you call it. It returns a new UIImage. All UIImages can be drawn in different sizes, but a limited 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 from an image, as in this guide for iOS 5 .

The following code is the UIView drawRect method, which illustrates the difference between a regular UIImage and a stretchable UIImage image. The image used for stretch.png is taken 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

+22
source

I wrote a category method for 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 enter this into your UIImage category that you already have (or create a new one) it only supports old stretch resizing, if you need more complicated stretch resizing, you can only do this on iOS 5 using resizableImageWithCapInsets: directly

+13
source

All Articles