Cocoa Touch - UIButton Custom Form

How can I make the touch area of ​​a button the same image shape?
Let's say I have a custom button with the image of a triangle, how can I make sure that only touches inside this triangle will be processed.

Or do I need to do some math in the on touch function?

+3
source share
3 answers

OBShapedButton is a great project for

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 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 the category method that is attached.

+3
source

cocoa , UIButton. , UIButton , .

+1

Ole OBShapedButton SO. vikingosegundo, my-programming-examples github , , , UIButton. .

  • UIImage + ColorAtPixel.h/m OBShapedButton.h/m
  • , .m >
  • UIButton OBShapedButton IB
  • , .png ""

, UIButtons, , UIView UIButton (, IB a > Arrange > Send to Back/). , OBShapedButton UIView, UIView OBShapedButton, UIView, OBShapedButton, UIViews . /p >

Ole viking ...... DO IT!

+1

Source: https://habr.com/ru/post/1774455/


All Articles