我想用 Swift 以编程方式创建 Hexagon UIButton。我有六边形图像,你可以看到绿色图片。边缘是透明的,所以你不应该点击那个区域。通过使用带有“自定义”选项的默认 UIButton,这些区域仍然可以点击。
然后像下图那样在 UIScrollView 上添加它们。最主要的是,当用户单击一个按钮时,我应该获得正确的按钮 ID。
那么,你能帮我创建六边形 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/