Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

enter image description here

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..

like image 994
DShah Avatar asked Nov 30 '22 15:11

DShah


1 Answers

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.

like image 173
Maulik Avatar answered Dec 07 '22 00:12

Maulik