2010-06-14 152 views

回答

141

尝试用代码做:

的Objective-C:

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

斯威夫特:

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

或地方的标签后面的UIImageView(不推荐)。不推荐将标签后面的UIImageView的,因为那时你将不得不管理两个观点:


更新。但是如果你必须做一些只有UIImageView可以做到的事情,这仍然是一个好方法。我怀疑你的应用程序实际上会以这种方式运行得更好。

+0

非常感谢。这正是我想要的。 – Joy 2010-06-14 14:17:04

+1

优秀和有用的功能,1up! :)但是我想知道苹果在将图像作为背景颜色实施时的想法。这完全违反直觉!即使CSS具有bg彩色图像的独立属性。也许这是过去Apple UI的一些遗产? – 2010-11-26 12:55:39

+4

经过测试,并且不支持PNG透明度。可能有一些窍门呢?我之前尝试将backgroundColor设置为clearColor,然后将其设置为图像,仅用于运动。但是,当然没有效果。 – 2010-11-26 13:16:36

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]; 
+0

它的工作原理,但由于某种原因,质量不符合预期。这是为什么? – Esqarrouth 2014-04-04 08:47:23

+0

@Esq如果您拉伸的图像会松动清晰度,而且看起来质量不如原始 – 2014-05-18 12:10:16

+0

九块拼接图像如何?这可以解决质量问题? – byJeevan 2015-03-11 15:14:30

0

雨燕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) 
-1

@pixelfreak,你的右手设置背景图片。具有彩色图像模式的UIColor实例在将其分配给背景色时具有严重的性能问题

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