3

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?

Community
  • 1
  • 1
user2397282
  • 3,798
  • 15
  • 48
  • 94
  • 1
    There is no quick solution to this built in to the framework. It is basically going to consist of detecting the exact pixel location of the touch, then converting the view to an image, and finally testing the right pixel of the image for what color it is. (you would probably want to cache the image if the view isn't changing). You can search for each of those things separately to build your solution. – drewag Jul 12 '14 at 17:37

1 Answers1

4

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.
}
Community
  • 1
  • 1
ujell
  • 2,792
  • 3
  • 17
  • 23