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
This feature is definitely not provided by the core cocoa touch classes related to a UIButton. I would guess you would have to look into subclassing UIButton and intercepting the taps as you mentioned.
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.
Ole's OBShapedButton project should be referenced more on SO. Thanks to vikingosegundo, who's my-programming-examples github has helped in the past, you can see some of what Ole put together to take away the actions from the transparent background part of a custom UIButton. I added this to my project and was able to get it up and running with these steps.
This project will help anyone who has multiple overlapping UIButtons that have a transparent backgrounds, even if they are in different UIViews or completely covered by another UIButton (e.g you can't select it in IB without Editor > Arrange > Send to Back/Front). However, if you have a OBShapedButton in a UIView, where part of the transparent UIView is overlapping an OBShapedButton, you can not receive the click or drag event on the UIView covered part of the OBShapedButton, so layer your UIViews with this in mind.
Download Ole and viking's projects for your tutorial collection......DO IT!