DShah DShah - 1 year ago 120
Objective-C Question

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

I have simple View based application. I had taken only

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
. 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
only.... no other control except
i want to use..

Answer Source

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();

    testLabel.backgroundColor = [UIColor colorWithPatternImage:newImage];

I have tested this code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download