Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone: How to extend a repeatable UIImage?

I have an image which I use to frame a tweet. It consists of two rounded rects, with a twitter icon a the top left. The important part is that it is repeatable, as you could copy any part of the middle section vertically, and it would be the same, just longer. Here is the image I created:

Tweet Frame

My question is how, in code, do I extend (or shrink) that dependent on how many lines are in my UITextView? Something like this to get the size:

float requiredHeight = lines * 14;

I know this is possible, because apple do it with their SMS app :)


UPDATE: Here is the complete code for doing this:

UIImage *loadImage = [UIImage imageNamed:@"TwitPost.png"];
float w2 = loadImage.size.width/2;
float h2 = loadImage.size.height/2;
// I have now reduced the image size so the height must be offset a little (otherwise it stretches the bird!):
loadImage = [loadImage stretchableImageWithLeftCapWidth:w2 topCapHeight:h2+15];
imageView.image = loadImage;

Thanks for both answers.

like image 819
Alex Coplan Avatar asked Dec 27 '22 16:12

Alex Coplan


2 Answers

By using

- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight

Where you set leftCapWidth and topCapHeight as half the width and height of your image. This image you can stretch in a UIImageView by changing its bounds/frame.

like image 131
Joris Mans Avatar answered Dec 30 '22 05:12

Joris Mans


Look at the documentation for UIImage. Specifically:

- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight

This allows you to use an image which repeats the portion at the leftCapWidth or topCapHeight to stretch it horizontally or vertically.

like image 45
simon aplin Avatar answered Dec 30 '22 06:12

simon aplin