2010-11-12 60 views
3

如何使可觸摸按鈕區域與所提供圖像的形狀相同?
說我有一個三角形圖像的自定義按鈕,我怎麼才能確保只有在該三角內的觸摸將被處理。Cocoa Touch - 自定義UIButton形狀

或者我必須在觸摸動作功能中做某種算術嗎?

+0

我你決定攔截水龍頭,蘋果已經爲你做了所有的數學。查看'UIBezierPath'的containsPoint:'方法(http://developer.apple.com/library/ios/documentation/uikit/reference/UIBezierPath_class/Reference/Reference.html#//apple_ref/occ/instm/UIBezierPath/ containsPoint :) – cobbal 2010-11-12 06:01:12

回答

1

此功能絕對不是由與UIButton相關的核心可可觸摸類提供的。我想你會不得不考慮子類化UIButton並攔截你提到的水龍頭。

3

OBShapedButton是針對

一個偉大的項目它的工作原理通過繼承的UIButton和壓倒一切的-pointInside:withEvent:

@implementation OBShapedButton 

// UIView uses this method in hitTest:withEvent: to determine which subview 
// should receive a touch event. 
// If pointInside:withEvent: returns YES, then the subview’s hierarchy is 
// traversed; otherwise, its branch 
// of the view hierarchy is ignored. 
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event 
{ 
    // Return NO if even super returns NO (i.e. if point lies outside our bounds) 
    BOOL superResult = [super pointInside:point withEvent:event]; 
    if (!superResult) { 
     return superResult; 
    } 

    // We can't test the image's alpha channel if the button has no image. 
    // Fall back to super. 
    UIImage *buttonImage = [self imageForState:UIControlStateNormal]; 
    if (buttonImage == nil) { 
     return YES; 
    } 

    CGColorRef pixelColor = [[buttonImage colorAtPixel:point] CGColor]; 
    CGFloat alpha = CGColorGetAlpha(pixelColor); 
    return alpha >= kAlphaVisibleThreshold; 
} 

@end 

[aUIImage colorAtPixel:point]是連接一個類別的方法。

1

Ole的OBShapedButton項目應該在SO上引用更多。感謝vikingosegundo,github曾幫助過my-programming-examples,你可以看到一些Ole將什麼東西從定製的UIButton的透明背景部分拿走。我將它添加到了我的項目中,並能夠通過這些步驟啓動並運行它。

  1. 下載項目
  2. 文件添加的UIImage + ColorAtPixel.h/m和OBShapedButton.h/m到項目文件夾
  3. 確保.m文件添加到您的目標的構建階段>編譯源列表
  4. 變化IB的UIButton的類類型所有的按鈕將OBShapedButton類
  5. 確保您的PNG文件具有透明背景,使之成爲該按鈕的「圖像」

這個項目將幫助任何具有多個重疊的UIButtons的具有透明背景的人,即使他們在不同的UIViews中或完全由另一個UIButton覆蓋(例如,如果沒有Editor> Arrange> Send> Send /面前)。但是,如果在UIView中有一個OBShapedButton,其中透明UIView的一部分與OBShapedButton重疊,則無法在OBShapedButton的UIView覆蓋部分接收到單擊或拖動事件,因此請牢記層層設置UIView。

下載Ole和維京的項目爲您的教程收集......做它!