【问题标题】:How to create programatically Hexagon UIButton or Clickable ImageView with Swift如何使用 Swift 以编程方式创建 Hexagon UIButton 或 Clickable ImageView
【发布时间】:2015-02-01 04:25:28
【问题描述】:

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

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

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

【问题讨论】:

    标签: swift uiscrollview uibutton hexagonal-tiles clickable-image


    【解决方案1】:

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

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

    如果 alpha 分量为 0,命中测试将失败。
    如果 alpha 不为零,则命中测试将成功。
    如果触摸超出按钮范围,命中测试也会失败。

    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
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-27
      • 2016-09-28
      • 2010-11-25
      • 2015-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多