问题
I have simple View based application. I had taken only UILabel
on it.
Following is my code in viewDidLoad:
lblBack.textColor = [UIColor blueColor];
UIImage *img = [UIImage imageNamed:@"cn3.png"];
lblBack.backgroundColor = [UIColor colorWithPatternImage:img];
lblBack.text = @"Hello World!!!...";
// UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
//
// CGRect rect = CGRectMake(0, 0, lblBack.frame.size.width, lblBack.frame.size.height);
// [imgView setFrame:rect];
// NSLog(@"Rect : %@",NSStringFromCGRect(rect));
// [img drawInRect:rect];
// imgView.contentMode = UIViewContentModeScaleAspectFill;
// imgView.contentMode = UIViewContentModeScaleAspectFit;
// imgView.contentMode = UIViewContentModeScaleToFill;
// [lblBack addSubview:imgView];
Comments shows some of the things that i have tried. I am getting following output:

In this one image is repeated 3 times. But I want that image should be stretched to fill the Label width.
I have referred some of the previous links that shows me to add Image in background and use clearColor
for UILabel
. Also seen example of Adding custom view in Background. But all this I dont want to use unless I dont have other solutions...
I just want to perform all things on UILabel
only.... no other control except UIImage
or UIImageView
i want to use..
回答1:
Dhiren try this code :
UIImage *img = [UIImage imageNamed:@"cab.png"];
CGSize imgSize = testLabel.frame.size;
UIGraphicsBeginImageContext( imgSize );
[img drawInRect:CGRectMake(0,0,imgSize.width,imgSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
testLabel.backgroundColor = [UIColor colorWithPatternImage:newImage];
I have tested this code.
回答2:
Porting over Maulik's answer to Swift 2.2, you get the following code:
var img: UIImage = UIImage(named: "cabImage")!
var imgSize: CGSize = testLabel.frame.size
UIGraphicsBeginImageContext(imgSize)
img.drawInRect(CGRectMake(0, 0, imgSize.width, imgSize.height))
var newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
testLabel.backgroundColor = UIColor(patternImage: newImage)
Personally tested to be working!
来源:https://stackoverflow.com/questions/8634083/how-to-stretch-image-to-fill-the-label-width-set-in-background-in-uilabel