2010-08-04 126 views
4

我想像尺寸30 * 28,其被放置在按鈕圖像的徽章上的圖像顯示的數字,如何設置背景圖像標記

我有一個徽章圖像來設置上的頂按鈕圖像.. 徽章圖像上我應該能夠顯示文本或數字,我的徽章大小是30 * 28 ...

因此,爲了實現我想在我的按鈕上設置標籤圖像,所以我想設置標籤背景的一些圖像稱爲徽章圖像

回答

10

無法將背景圖片添加到一個UILabel,但您可以添加一個UIImageView作爲子視圖一個UILabel。確保UILabel的透明度爲backgroundColor = [UIColor clearColor];

E.g.

UIImageView *labelBackground = [[UIImageView alloc] 
    initWithImage:[UIImage imageNamed:@"mybg.png"]]; 
[myLabel addSubview:labelBackground]; 
[labelBackground release]; 
myLabel.backgroundColor = [UIColor clearColor]; 

應該工作。未經測試。

+0

但標籤文本是不可見的。只有圖像出現。 – prajul 2012-01-06 16:08:55

+1

錯誤的答案,背景圖片可以添加到uilabels!不鼓勵將UIImage添加爲子視圖以提供「背景」效果。 – 2012-11-05 13:22:09

+0

隨意使用的措辭「過時的答案」的答案2年前是正確的,當它被張貼。 ;)也就是說,如果人們想要與舊版iOS兼容:它們可能仍然會發現這個答案很有用。 – Kalle 2012-11-07 16:25:56

10

看到這個堆棧溢出本身上面的代碼只是給沒有標籤

對我來說 有用的,共享

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

看到背景:Adding Background image to UILabel

1

要使圖像適合你的UIView試試這個代碼

UIImage *backgroundImage = [UIImage imageNamed:@"imageNameHere"]; 

UIGraphicsBeginImageContext(self.labelName.frame.size); 
[backgroundImage drawInRect:CGRectMake(0, 0, self.labelName.frame.size.width, self.labelName.frame.size.height)]; 
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

self.labelName.backgroundColor = [UIColor colorWithPatternImage:newImage];