我创建了一个自定义 UIButton 子类,其行为与您所描述的完全一样,看看:https://github.com/spagosx/iOS-Shaped-Button-Swift https://github.com/spagosx/iOS-Shaped-Button-Swift
它是用 Swift 编写的,但可以轻松转换为 Objective-c。
方法是从触摸点获取像素数据并访问 RGBA 值,在本例中我们读取 A (alpha) 并检查它是否高于我们的阈值。
看一段代码:
func alphaFromPoint(point: CGPoint) -> CGFloat {
var pixel: [UInt8] = [0, 0, 0, 0]
let colourSpace = CGColorSpaceCreateDeviceRGB()
let alphaInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
let context = CGContext(data: &pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colourSpace, bitmapInfo: alphaInfo.rawValue)
context?.translateBy(x: -point.x, y: -point.y)
self.layer.render(in: context!)
let floatAlpha = CGFloat(pixel[3])
return floatAlpha
}
你可以采取floatAlpha
值并将其与您可接受的 alpha 值进行比较:
override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
return self.alphaFromPoint(point) >= 100
}