How to stretch image to fill label width in background in UILabel?

I have a simple View based application. I took only UILabel .

Below 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]; 

The comments show some of the things I tried. I get the following output:

enter image description here

In this one image is repeated 3 times. But I want the image to be stretched to fill the width of the label.

I mentioned some of the previous links that show me to add an image in the background and use clearColor for UILabel . An example of adding a custom view to Background is also shown. But I don’t want to use all this if I have no other solutions ...

I just want to execute everything on UILabel only .... no other control other than UIImage or UIImageView , I want to use ..

+4
source share
2 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 checked this code.

+20
source

Porting Maulik's answer to Swift 2.2 gives you 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 work!

+1
source

Source: https://habr.com/ru/post/1387993/


All Articles