I am using Xcode 6 Beta with Swift, and I want to create a method that is called when a finger on the screen touches a certain UIColour, such as grey.
How do I do that?
I am using Xcode 6 Beta with Swift, and I want to create a method that is called when a finger on the screen touches a certain UIColour, such as grey.
How do I do that?
This question was already answered for Objective-C. The code is just a little bit different in Swift but i converted it anyway;
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)
}
}
In your view controller;
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.
}