【发布时间】:2023-03-25 18:10:01
【问题描述】:
我正在使用带有 Swift 的 Xcode 6 Beta,我想创建一个方法,当屏幕上的手指触摸到某个 UIColour(例如灰色)时调用该方法。
我该怎么做?
【问题讨论】:
-
框架中没有内置的快速解决方案。它基本上包括检测触摸的确切像素位置,然后将视图转换为图像,最后测试图像的正确像素的颜色。 (如果视图没有改变,您可能希望缓存图像)。您可以分别搜索这些内容以构建您的解决方案。
我正在使用带有 Swift 的 Xcode 6 Beta,我想创建一个方法,当屏幕上的手指触摸到某个 UIColour(例如灰色)时调用该方法。
我该怎么做?
【问题讨论】:
Objective-C 已经回答了这个问题。 Swift 中的代码有点不同,但我还是转换了它;
extension UIView
{
func colorOfPoint (point: CGPoint) -> UIColor
{
var pixel = UnsafePointer<CUnsignedChar>.alloc(4)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo.fromRaw(CGImageAlphaInfo.PremultipliedLast.toRaw())!
let context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, bitmapInfo)
CGContextTranslateCTM(context, -point.x, -point.y)
self.layer.renderInContext(context)
CGContextRelease(context)
CGColorSpaceRelease(colorSpace)
return UIColor(red: Float(pixel [0]) / 255.0, green: Float (pixel [1]) / 255.0, blue: Float (pixel [2]) / 255.0 , alpha: Float (pixel [3]) / 255.0)
}
}
在您的视图控制器中;
override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!)
{
let touch : UITouch = event.allTouches().anyObject() as UITouch
let location = touch.locationInView(self.view)
pickedColor = self.view.colorOfPoint (location)
// Do something with picked color.
}
【讨论】: