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

前端 未结 2 689
暖寄归人
暖寄归人 2020-12-25 09:24

I have simple View based application. I had taken only UILabel on it.

Following is my code in viewDidLoad:

lblBack.textColor = [UIColo         


        
相关标签:
2条回答
  • 2020-12-25 09:45

    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.

    0 讨论(0)
  • 2020-12-25 09:50

    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!

    0 讨论(0)
提交回复
热议问题