Xcode Swift - 检测屏幕上的颜色触摸

时间:2014-07-12 14:45:39

标签: touch swift uicolor

我正在使用Swift的Xcode 6 Beta,我想创建一个方法,当屏幕上的手指触摸某个UIColour时会调用该方法,例如灰色。

我该怎么做?

1 个答案:

答案 0 :(得分:4)

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