Ios 将背景图像添加到UILabel

Ios 将背景图像添加到UILabel,ios,Ios,如何在iPhone应用程序中向UILabel添加背景图像。我曾尝试通过IB执行此操作,但没有结果。尝试使用代码执行此操作: 目标-C: theLabel.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"blah"]]; theLabel.backgroundColor = UIColor(patternImage: UIImage(named: "blah")!) Swift: theLabel.b

如何在iPhone应用程序中向UILabel添加背景图像。我曾尝试通过IB执行此操作,但没有结果。

尝试使用代码执行此操作:

目标-C:

theLabel.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"blah"]];
theLabel.backgroundColor = UIColor(patternImage: UIImage(named: "blah")!)
Swift:

theLabel.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"blah"]];
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];

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)

@像素怪胎,你的权利。具有彩色图像图案的UIColor实例在将其指定给backroundcolor时存在严重的性能问题

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

卓越且有用的功能,1up!:)但我想知道,当苹果将这张图片作为背景色时,它是怎么想的。这完全违反直觉!甚至CSS对bg的彩色图像也有单独的属性。也许这是过去苹果用户界面的遗留问题?经过测试,它不支持PNG透明。可能有什么把戏?我确实试过在将背景色设置为图像之前将其设置为clearColor,只是为了运动。但当然没有效果。要使用透明PNG,必须将UILabel不透明属性设置为no:
[theLabel SetOkable:no]我可以知道为什么不建议在label控件后面使用UIImageView吗?提前感谢。我在某个地方读到,使用
colorWithPatternImage
具有性能含义。它可以工作,但由于某些原因,质量不如预期。为什么会这样?@Esq如果你拉伸一张图像,它的清晰度会变差,而且看起来不像原始图像那么高质量。九块补丁图像怎么样?这可以解决质量问题?关于质量,很简单,只需使用
UIGraphicsBeginImageContextWithOptions(u,u,0)
(最后一个参数是图像比例->0=auto)。