我该如何在 iPhone 应用中为 UILabel 添加背景图片?我尝试通过 IB 进行操作,但没有成功。
试着用代码实现:
Objective-C:
theLabel.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"blah"]];
Swift:
theLabel.backgroundColor = UIColor(patternImage: UIImage(named: "blah")!)
或者在标签后面放置一个UIImageView
(不建议这样做)。
更新:将UIImageView
放在标签后面并不被推荐,因为这样你就需要管理两个视图。但是,如果你必须要做一些只有UIImageView
才能做到的事情,那么这仍然是一个不错的方法。我猜测用这种方式运行你的应用程序实际上会更好。
如果您想让图像被拉伸以填满标签的宽度。 尝试这段代码。
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];
UIGraphicsBeginImageContextWithOptions(_, _, 0)
即可(最后一个参数为图像比例-> 0 = 自动)。 - VagnerSwift 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)
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
}
@pixelfreak,你说得对。使用带有颜色图案的UIColor实例在分配给背景颜色时会出现严重的性能问题。
cell.cellLabel.backgroundColor = UIColor(patternImage: UIImage(named: "background")!)
[theLabel setOpaque:NO];
- DreamwiebercolorWithPatternImage
会对性能产生影响。 - pixelfreak