views:

66

answers:

1

Hi, 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:

  1. You are apparently leaking image. There appears no reason to retain it.
  2. Do not use the initializer ( init WithImage:) on an already initialized object. Use setImage: or the image property instead.
tonklon
Hi, thanks for your help and notes. I've made the changes, but the Bg.png image scale is still wrong.At least now it is in the right size, but the scale is not proportional. perhaps I should fix some properties of the UIImageView itself?
Chen Harel
Hi - I've played with it a bit more and now it seems to work.My guesses are that stretchableImageWithLeftCapWidth needed some more pixels.
Chen Harel