2013-02-07 15 views
4

如何在給定圖像的形狀中創建UIButton。以給定圖像的形狀創建UIButton

我能夠創造出接近它的東西,但圖像似乎不適合按鈕。 我的要求是下面給出的圖像.i.e;半圓

我用來創建按鈕的代碼如下。

我應該在下面的圖片上做些什麼改變才能得到這個按鈕。 PS-ADD子視圖另一類做..

btnStartGame =[UIButton buttonWithType:UIButtonTypeCustom]; 
[btnStartGame setFrame:CGRectMake(60, 200, 200, 200)]; 

btnStartGame.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:30]; 
[btnStartGame setImage: 
[UIImage imageNamed:@"Draw button.png"] forState:UIControlStateNormal]; 

btnStartGame.titleLabel.textColor=[UIColor redColor]; 
btnStartGame.clipsToBounds = YES; 
btnStartGame.layer.cornerRadius = 50;//half of the width 
btnStartGame.layer.borderColor=[UIColor redColor].CGColor; 
btnStartGame.layer.borderWidth=2.0f; 

btnStartGame.tag=20; 
btnStartGame.highlighted=NO; 
+0

你嘗試了什麼? – nielsbot

+1

我忘記提及最重要的事情,點擊按鈕不應該超出圖像...嚴格的圖像內.. –

+1

它的東西,但我開發一個小遊戲的開始畫面。我必須去主頁點擊這個按鈕後,但當我爲這個集成圖形,我有這個問題,我可以創建一個類似的按鈕,但現在的問題是,如果我點擊按鈕圖像外的部分(這應該是按鈕)它是一個click.pls幫助 –

回答

2

有一個真正偉大的教程這裏下載的源代碼:

http://iphonedevelopment.blogspot.co.uk/2010/03/irregularly-shaped-uibuttons.html

在您需要創建UIImage的一個類別的本質,它會檢查您觸摸的點是否爲透明圖像。這意味着您可以使用它來檢查不規則形狀上的命中測試。

然後,您可以繼承的UIButton和過度騎則hitTest:withEvent:方法

希望這有助於

+0

你可能想'接受'的答案,然後;-) – Tim

+1

偉大的教程傢伙...這是完全working.i從程序中複製2類OBShapedButton和UIImage + ColorAtPixel,導入它們到我的程序,並使按鈕成爲'OBShapedButton類'的實例。它僅檢測到圖像,並且我提到的問題沒有發生。我還在我給出的代碼中註釋了以下幾行代碼即 –

+0

btnStartGame.clipsToBounds = YES; btnStartGame.layer.cornerRadius = 50; //寬度的一半 btnStartGame.layer.borderColor = [UIColor redColor] .CGColor; btnStartGame.layer.borderWidth = 2.0f;任何人都可以使用此方法創建任何形狀的按鈕,並按照我所做的一樣完成任務。 –

1

雖然傑夫·拉馬什通過對方的回答鏈接的解決方案正常工作,它使用了大量的內存, /或做了很多工作:

  • 如果在初始創建NSData一次,你最終持有的內存比較大的塊爲每個按鈕
  • 如果溜溜的壽命你可以使它瞬變,它在答案中完成的方式,然後你每次點擊測試按鈕時都會轉換整個圖像 - 處理成千上萬像素並在獲取單個字節後丟棄結果!

事實證明,通過遵循this answer中列出的方法,您可以更高效地完成此操作,無論是在內存使用情況還是CPU消耗方面。

子類UIButton,並覆蓋其pointInside:withEvent:方法是這樣的:

-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event { 
    if (![super pointInside:point withEvent:event]) { 
     return NO; 
    } 
    unsigned char pixel[1] = { 0 }; 
    CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 1, NULL, (CGBitmapInfo)kCGImageAlphaOnly); 
    UIGraphicsPushContext(context); 
    UIImage *image = [self backgroundImageForState:UIControlStateNormal] ; 
    [image drawAtPoint:CGPointMake(-point.x, -point.y)]; 
    UIGraphicsPopContext(); 
    CGContextRelease(context); 
    return pixel[0] != 0; 
} 

上述代碼發生阿爾法從按鈕的背景圖像。如果您的按鈕使用其他圖像,請更改上面初始化變量image的行。