Cocoa Touch - 自定义UIButton形状 [英] Cocoa Touch - Custom UIButton shape

查看:181
本文介绍了Cocoa Touch - 自定义UIButton形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使可触摸按钮区域与提供的图像具有相同的形状?

说明我有一个带有三角形图像的自定义按钮,如何确保只触摸

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 touches within that triangle will be processed.

或者我必须在触摸操作函数中做一些计算吗?

Or do I have to do some kind of math in the on touch action function?

推荐答案

OBShapedButton 是一个非常棒的项目

它通过子类化UIButton并覆盖 -pointInside:withEvent:

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] 是附加的类别方法。

这篇关于Cocoa Touch - 自定义UIButton形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆