Cocoa Touch - Custom UIButton shape

后端 未结 3 1636
无人及你
无人及你 2020-12-06 14:53

How can I make the touchable button area to be of the same shape of the image provided?
Say I have a custom button with a triangle image, how can I make sure that only t

3条回答
  •  再見小時候
    2020-12-06 15:41

    OBShapedButton is a great Project for that

    It works by subclassing UIButton and overriding -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] is a category-method that is attached.

提交回复
热议问题