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

标签 swift uiscrollview uibutton hexagonal-tiles clickable-image

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

然后像下图那样在 UIScrollView 上添加它们。最主要的是,当用户单击一个按钮时,我应该获得正确的按钮 ID。

Example

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

最佳答案

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

我们在触摸点处检测图像的 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
        }
    }
}

关于swift - 如何使用 Swift 以编程方式创建 Hexagon UIButton 或 Clickable ImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28259463/

相关文章:

swift - 如何在集合扩展中返回空子序列

ios - uikeyboardwillhidenotification 滚动时调用方法两次

json - 如何给一些时间(60 秒)快速重新发送 OTP 按钮

ios - 同时点击两个按钮,如果一个覆盖另一个

ios - 使用 UIBarButtonItem 连续调用一个函数

ios - 如何以编程方式将 UICollectionView 添加到容器?

swift - LLDB 输出错误 : use of undeclared type '$__lldb_context'

ios - 如何从子类 UITableViewCell 调用 didSelectRowAtIndexPath

iphone - 缩短 UIScrollView 中的触摸延迟?

ios - 更改 UITextfield 输入的宽度