2012-10-18 32 views
0

我有我的代表按鈕,如下圖:如何使用圖像作爲按鈕背景?

enter image description here

我想使用圖片來創建使用作爲背景,但比我提供的圖像更廣泛的按鈕。

下面是我曾嘗試兩種方法:

UIButton *emailSupportButton = [[UIButton alloc] initWithFrame:CGRectMake(25, 315, 200, 60)]; 
    [emailSupportButton setTitle:@"Email Support" forState:UIControlStateNormal]; 
    [emailSupportButton setImage:[UIImage imageNamed:@"toolbar-button"] forState:UIControlStateNormal]; 

按鈕圖像中的方法結果未拉伸和準確顯示如何.PNG通常顯示。

我已經試過被設置背景圖像,像這樣的另一種方法...

UIButton *emailSupportButton = [[UIButton alloc] initWithFrame:CGRectMake(25, 315, 200, 60)]; 
    [emailSupportButton setTitle:@"Email Support" forState:UIControlStateNormal]; 
    [emailSupportButton setBackgroundImage:[UIImage imageNamed:@"toolbar-button"] forState:UIControlStateNormal]; 

這種方法在一個非常醜陋的方式拉伸圖像,而不是達到預期的效果,導致該按鈕被幾乎是橢圓形,邊界非常醜陋。

問題是我沒有使用正確的方法創建自定義按鈕,或者我的圖像不適合我嘗試完成的任務?我的圖片應該是矩形的,不包括按鈕的邊框,讓UIButton爲我處理邊框/四捨五入嗎?我的圖像應該已經是按鈕的大小了(這似乎有點限制)?

回答

1

您列出的第二種方法(代碼方式)是您想要的。你缺少的是可拉伸的圖像。如果您在iOS 5和更大的部署

UIButton *emailSupportButton = [[UIButton alloc] initWithFrame:CGRectMake(25, 315, 200, 60)]; 
[emailSupportButton setTitle:@"Email Support" forState:UIControlStateNormal]; 
UIImage *backgroundImage = [UIImage imageNamed:@"toolbar-button"]; 
CGSize size = backgroundImage.size; 
backgroundImage = [backgroundImage stretchableImageWithLeftCapWidth:size.width/2.0 topCapWidth:size.height/2.0]; 
[emailSupportButton setBackgroundImage:backgroundImage forState:UIControlStateNormal]; 

而已,那麼你將要使用的新-[UIImage resizableImageWithCapInsets:(UIEdgeInsets)capInsets];的iOS 6還增加了-[UIImage resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode];

+0

哇真棒,謝謝:試試這個!這正是我正在尋找的。 – MikeS

相關問題