How to know that if the only visible area of a .png is touched in Xcode(如何知道是否在 Xcode 中触摸了 .png 的唯一可见区域)
问题描述
我已经在 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 的唯一可见区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何知道是否在 Xcode 中触摸了 .png 的唯一可见区域
基础教程推荐
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01