How to stretch Image to fill the Label Width set in Background in UILabel?

隐身守侯 提交于 2019-12-18 10:57:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!