Linux world
Linux world

Reputation: 3768

How to set a background image to label

I want to display a number on image like badge of size 30*28, which is placed upon button image,

I have an badge image to set up on the top of button image.. on top of badge image I should able to display text or number and my badge size is 30*28.

so, for this to achieve I want to set a label on top of my button image and so I want to set label background to some image called badge image.

Upvotes: 4

Views: 18889

Answers (3)

Ram Madhavan
Ram Madhavan

Reputation: 2388

To make the image fit in your UIview, try this code

UIImage *backgroundImage = [UIImage imageNamed:@"imageNameHere"];

UIGraphicsBeginImageContext(self.labelName.frame.size);
[backgroundImage drawInRect:CGRectMake(0, 0, self.labelName.frame.size.width, self.labelName.frame.size.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

self.labelName.backgroundColor = [UIColor colorWithPatternImage:newImage];

Upvotes: 1

darkmystel
darkmystel

Reputation: 198

found this in stack overflow itself as the above code just gives the background without the label

was useful for me so sharing

theLabel.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"blah"]];

See: Adding Background image to UILabel

Upvotes: 11

Kalle
Kalle

Reputation: 13346

You can't add a background image to a UILabel, but you can add a UIImageView as a subview to a UILabel. Make sure the UILabel has backgroundColor = [UIColor clearColor]; for transparency.

E.g.

UIImageView *labelBackground = [[UIImageView alloc] 
    initWithImage:[UIImage imageNamed:@"mybg.png"]];
[myLabel addSubview:labelBackground];
[labelBackground release];
myLabel.backgroundColor = [UIColor clearColor];

Should work. Untested.

Upvotes: 10

Related Questions