问题描述
我已经在 Xcode 中的 UIImageView
中导入了一个 .png 图像,我想做的是当图像被触摸时,它将被隐藏.
I have imported a .png image into UIImageView
in Xcode and what I want to make is when the image is touched, it will be hidden.
但我的问题是 png 图像包含透明部分,当我触摸透明部分时,动作会继续.我希望仅在触摸图像的可见部分时才进行操作.如何解决问题?
But my problem is that the png image contains transparent parts and when I touch on the transparent parts, the action goes on. I want the action to go on only when the visible part of the image is touched. How to solve the problem?
Swift 或 Objective-C
Swift or Objective-C
推荐答案
我创建了一个自定义 UIButton 子类,它的行为与您描述的完全一样,看看:https://github.com/spagosx/iOS-Shaped-Button-Swift
I have created a custom UIButton subclass that behaves exactly as you describe, have a look: https://github.com/spagosx/iOS-Shaped-Button-Swift
它是用 Swift 编写的,但很容易转换为 Objective-c.
It's written in Swift, but it's easily convertible to Objective-c.
方法是从触摸点获取像素数据并访问 RGBA 值,在这种情况下,我们读取 A (alpha) 并检查它是否高于我们的阈值.
The approach is to get the pixel data from the touch point and to access the RGBA values, in this case we read A (alpha) and check if it is higher than our threshold.
看一点代码:
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 值进行比较:
You can than take the floatAlpha
value and compare it with your acceptable value of alpha:
override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
return self.alphaFromPoint(point) >= 100
}
这篇关于如何知道是否在 Xcode 中触摸了 .png 的唯一可见区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!