我正在使用带有Swift的Xcode 6 Beta,我想创建一个在屏幕上的手指触摸特定颜色(如灰色)时调用的方法。
我该怎么做?
这个问题已经在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.
}