将背景图像添加到UILabel

时间:2010-06-14 14:10:15

标签: ios

如何在iPhone应用程序中向UILabel添加背景图像。我试图通过IB做到但没有结果。

5 个答案:

答案 0 :(得分:146)

尝试使用代码:

<强>目标-C:

theLabel.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"blah"]];

<强>夫特:

theLabel.backgroundColor = UIColor(patternImage: UIImage(named: "blah")!)

或在标签后面放置UIImageView(不推荐)。


更新:不推荐在标签后面放置UIImageView,因为那时你必须管理两个视图。但是如果你必须做一些只有UIImageView可以做到的事情,这仍然是一个很好的方法。我怀疑你的应用程序实际上会以这种方式运行得更好。

答案 1 :(得分:18)

如果您希望拉伸图像以填充标签宽度。 试试这段代码。

UILabel *myLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 20)];

UIImage *img = [UIImage imageNamed:@"a.png"];
CGSize imgSize = myLabel.frame.size;

UIGraphicsBeginImageContext( imgSize );
[img drawInRect:CGRectMake(0,0,imgSize.width,imgSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

myLabel.backgroundColor = [UIColor colorWithPatternImage:newImage];

答案 2 :(得分:0)

Swift 2.2:使用背景颜色设置背景图像

    UIGraphicsBeginImageContextWithOptions(stationNameLabel.frame.size, false, 0.0)

    let context = UIGraphicsGetCurrentContext();

    let components = CGColorGetComponents(color.CGColor)

    CGContextSetRGBFillColor(context, components[0], components[1], components[2], 0.4);
    CGContextFillRect(context, CGRectMake(0.0, 0.0, stationNameLabel.frame.size.width, stationNameLabel.frame.size.height));


    targetImage.drawInRect(CGRectMake(0.0, 0.0, stationNameLabel.frame.size.width, stationNameLabel.frame.size.height))
    let resultImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    label.backgroundColor = UIColor(patternImage: resultImage)

答案 3 :(得分:0)

 let messageBackgroundView = UIImageView()
        messageBackgroundView.image = UIImage(named: "chat-background")
        if messageBackgroundView.superview != lblChatdata.superview {
            lblChatdata.superview!.insertSubview(messageBackgroundView, belowSubview: lblChatdata)
            messageBackgroundView.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                messageBackgroundView.leadingAnchor.constraint(equalTo: lblChatdata.leadingAnchor),
                messageBackgroundView.trailingAnchor.constraint(equalTo: lblChatdata.trailingAnchor),
                messageBackgroundView.topAnchor.constraint(equalTo: lblChatdata.topAnchor),
                messageBackgroundView.bottomAnchor.constraint(equalTo: lblChatdata.bottomAnchor),
                ])
            messageBackgroundView.contentMode = .scaleAspectFill
        }

答案 4 :(得分:-1)

@pixelfreak,你的权利。具有彩色图像模式的UIColor实例在将其分配给backroundcolor时存在严重的性能问题

cell.cellLabel.backgroundColor = UIColor(patternImage: UIImage(named: "background")!)