如何使用 Swift 以编程方式创建 Hexagon UIButton 或 Clickable ImageView

How to create programatically Hexagon UIButton or Clickable ImageView with Swift

我想用 Swift 以编程方式创建 Hexagon UIButton。我有六边形图像,你可以看到绿色图片。边缘是透明的,所以你不应该点击那个区域。通过使用带有 "custom" 选项的默认 UIButton,这些区域仍然可以点击。

然后将它们添加到 UIScrollView 上,如下图所示。最主要的是,当用户点击一个按钮时,我应该得到正确的按钮 ID。

那么,你能帮我创建六边形 UIButton 或可点击的图像视图吗?谢谢

您可以扩展 UIButton class 以不检测图像透明部分的触摸事件。

我们在触摸点处检测图像的 alpha 分量。

If the alpha component is 0, the hit test will fail.
If the alpha is non zero, hit test will succeed.
The hit test will also fail if the touch is outside the button bounds.

extension UIButton {

    func getColourFromPoint(point:CGPoint) -> UIColor {
            let colorSpace:CGColorSpace = CGColorSpaceCreateDeviceRGB()
            let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)

            var pixelData:[UInt8] = [0, 0, 0, 0]

            let context = CGBitmapContextCreate(&pixelData, 1, 1, 8, 4, colorSpace, bitmapInfo)
            CGContextTranslateCTM(context, -point.x, -point.y);
            self.layer.renderInContext(context)

            var red:CGFloat = CGFloat(pixelData[0])/CGFloat(255.0)
            var green:CGFloat = CGFloat(pixelData[1])/CGFloat(255.0)
            var blue:CGFloat = CGFloat(pixelData[2])/CGFloat(255.0)
            var alpha:CGFloat = CGFloat(pixelData[3])/CGFloat(255.0)

            var color:UIColor = UIColor(red: red, green: green, blue: blue, alpha: alpha)
            return color
    }

    public override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
        if (!CGRectContainsPoint(self.bounds, point)) {
            return nil
        }
        else {
            let color : UIColor = self.getColourFromPoint(point)
            let alpha = CGColorGetAlpha(color.CGColor);
            if alpha <= 0.0 {
                return nil
            }
            return self
        }
    }
}