Q:

Resizing a strechable image to match a UILabel sizeToFit

I'm trying to create a label with an image behind it. the image is a custom rectangle with rounded corners.
I read about the stretchableImageWithLeftCapWidth: to make sure the corners won't get scaled and about the sizeToFit to enlarge the UILabel frame.
Now the view as a whole: I have a UIView in IB, I added an ImageView with the image, and a UILabel on top of it. Both of them are centered (and should remain centered),
I call a function that will change the UILabel's text and should make the necessary changes to the frames.
Here is what I've been trying to do:
myLabel.text = hint;
    [myLabel sizeToFit];
    CGRect r = myLabel.frame;

    UIImage* image = [[UIImage imageNamed:@"Bg.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:5];
    [image retain];
    myImageView.frame = CGRectMake(r.origin.x - 5, r.origin.y - 5, r.size.width + 10, r.size.height + 10);
    [myImageView initWithImage:image];
    [self setNeedsDisplay];

What am I missing? and how can I make sure that when it works, the text and image will remain centered?
Thanks!

A:

You can make use of the center property on each UIView:
myImageView.center = CGPointMake(self.bounds.size.width/2,self.bounds.size.height/2);

This will center myImageView inside self vertically and horizontally. Use the same for your label. If your ImageView needs a larger Frame theres the more readable function CGRectInset()
myImageView.frame = CGRectInset(myLabel.frame, 10, 10);

By the way:

You are apparently leaking image. There appears no reason to retain it.
Do not use the initializer ( init WithImage:) on an already initialized object. Use setImage: or the image property instead.

