Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Background image to UILabel

Tags:

ios

How can I add a background image to a UILabel in an iPhone Application. I've tried to do it through IB but with no result.

like image 720
Joy Avatar asked Jun 14 '10 14:06

Joy


People also ask

How do I add a background image to a label?

This should do the trick: yourLabel. backgroundColor = UIColor(patternImage: UIImage(named: "backgroundImage")!)

How do I upload a picture to UILabel?

From there you can drag a UIImageView and UILabel into the view you just created. Set the image of the UIImageView in the properties inspector as the custom bullet image (which you will have to add to your project by dragging it into the navigation pane) and you can write some text in the label.


2 Answers

Try doing it with code:

Objective-C:

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

Swift:

theLabel.backgroundColor = UIColor(patternImage: UIImage(named: "blah")!) 

Or place an UIImageView behind the label (not recommended).


Update: placing an UIImageView behind a label was not recommended because then you would have to manage two views. But if you must do something that only an UIImageView can do this is still a good approach. I suspect that your app will actually run better this way.

like image 178
Evadne Wu Avatar answered Oct 07 '22 20:10

Evadne Wu


if you want that image should be stretched to fill the Label width. try this code.

UILabel *myLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 20)];  UIImage *img = [UIImage imageNamed:@"a.png"]; CGSize imgSize = myLabel.frame.size;  UIGraphicsBeginImageContext( imgSize ); [img drawInRect:CGRectMake(0,0,imgSize.width,imgSize.height)]; UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();  myLabel.backgroundColor = [UIColor colorWithPatternImage:newImage]; 
like image 23
Lê Trinh Avatar answered Oct 07 '22 19:10

Lê Trinh