James Anderson
James Anderson

Reputation: 566

Why won't UIImage stretch properly?

I am trying to stretch a UIImage with the following code:

UIImage *stretchyImage = [[UIImage imageNamed:@"[email protected]"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0];
UIImageView *newTag = [[UIImageView alloc] initWithImage:stretchyImage];

The image before stretching looks like this:

enter image description here

And after, looks like this:

enter image description here

Why hasn't the stretching worked properly? The corners have all gone pixelated and look stretched, when in fact only the middle should be stretched. FYI: I am running this app on iOS 6.

Upvotes: 2

Views: 2711

Answers (1)

Mert Dümenci
Mert Dümenci

Reputation: 513

Why your implementation doesn't work is because of the values you give to the stretchableImageWithLeftCapWidth:topCapHeight: method.

First of all, stretchableImageWithLeftCapWidth:topCapHeight: is deprecated with iOS 6. The new API is resizableImageWithCapInsets:

The image has non-stretchable parts on the top, bottom and the right sides. What you told the API was "get -10 from the left side, stretch the rest according to the size I give you".

Since you have a non-repeatable custom shape on the right side, by both height and width, we should take that piece as a whole.

So the top cap width should be the height of the image (to preserve the shape of the thing on the right side), left cap width should be ~20 pixels (rounded rectangle corners), the bottom cap can be 0, since the top cap is the whole image height, and finally the right cap should be the width of the custom orange shape on the right side (which I take as ~40 pixels).

You can play with the cap values and achieve a better result.

UIImage *image = [UIImage imageNamed:@"Tag"];
UIImage *resizableImage = [image resizableImageWithCapInsets:UIEdgeInsetsMake(image.size.height, 20, 0, 40)];

Should do the trick. Also, -imageNamed works fine when you get rid of the file extension & @2x.

Upvotes: 3

Related Questions