自定义形状可触摸区域

我有一个像下面的形状,我想把它设置为我的UIButton的背景, 可触摸的区域是一个矩形,任何建议改变可触摸的区域,以塑造寄宿生?

在此处输入图像描述

我们的想法是拥有一个UIButton的子类来覆盖以下方法:

func hitTest(_ point: CGPoint, withEvent event: UIEvent?) -> UIView? // that's for handling the case of multiple custom subviews on your view rather than for evaluating if it's your view to handle the touch 

 func pointInside(_ point: CGPoint, withEvent event: UIEvent?) -> Bool // way more preferable than hit test in your case!!! 

Objective-C中有一个教程,它使用命中测试(只是为了捕捉这个想法)。 在您的情况下,最难的问题是检测接收的触摸位置是否在您的自定义形状的范围内(上面的教程依赖于像素透明度,而不是您的情况)。 我假设你使用Bezier路径绘制形状。 如果这就是你所做的,你可以使用func containsPoint(_ point: CGPoint) -> Bool of UIBezierPath实现评估中的containsPoint(_ point: CGPoint) -> Bool 。 祝你好运。 关于UIBezierPath,PSThere也是一个棘手的问题:

如果该点位于打开的子路径内,则该路径不被视为包围该点,无论该区域是否在填充操作期间被绘制。 因此,要确定打开路径上的鼠标命中,必须先创建路径对象的副本,然后在调用此方法之前显式关闭所有子路径(使用closePath方法)。

实际上我发现它就像这样并完美地工作:

如何知道如果在XCode(swift或Objective C)中触及.png的唯一可见区域

必须更改如下代码:

  func alphaFromPoint(point: CGPoint) -> CGFloat { var pixel: [UInt8] = [0, 0, 0, 0] let colorSpace = CGColorSpaceCreateDeviceRGB(); let alphaInfo : CGBitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue) let context = CGBitmapContextCreate(&pixel, 1, 1, 8, 4, colorSpace, alphaInfo.rawValue) //need add .rawValue to alphaInfo CGContextTranslateCTM(context, -point.x, -point.y); self.layer.renderInContext(context!) let floatAlpha = CGFloat(pixel[3]) return floatAlpha 

}