How to get the pixel color on touch?

后端 未结 5 2141
闹比i
闹比i 2020-11-27 02:28

I know this is a common question and there are a lot of answers of this question. I\'ve used some of this. Although many of them are the same. But the sad thing for me is th

5条回答
  •  清酒与你
    2020-11-27 03:13

    Great answer rdelmar this helped me A LOT!

    Here is how I did the above in Swift:

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent)
        {
            var touch:UITouch = event.allTouches()!.anyObject() as UITouch
            var loc = touch.locationInView(self)
            var color:UIColor = getPixelColorAtPoint(loc)
            println(color)
        }
    
        //returns the color data of the pixel at the currently selected point
        func getPixelColorAtPoint(point:CGPoint)->UIColor
        {
            let pixel = UnsafeMutablePointer.alloc(4)
            var colorSpace = CGColorSpaceCreateDeviceRGB()
            let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
            let context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, bitmapInfo)
    
            CGContextTranslateCTM(context, -point.x, -point.y)
            layer.renderInContext(context)
            var color:UIColor = UIColor(red: CGFloat(pixel[0])/255.0, green: CGFloat(pixel[1])/255.0, blue: CGFloat(pixel[2])/255.0, alpha: CGFloat(pixel[3])/255.0)
    
            pixel.dealloc(4)
            return color
        }
    

提交回复
热议问题