How to get the pixel color on touch?

后端 未结 5 2139
闹比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 02:59

    Swift 4, Xcode 9 - With a UIImageView Extension

    This is a combination of all of the answers above but in an extension

    extension UIImageView {
        func getPixelColorAt(point:CGPoint) -> UIColor{
            
            let pixel = UnsafeMutablePointer.allocate(capacity: 4)
            let colorSpace = CGColorSpaceCreateDeviceRGB()
            let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
            let context = CGContext(data: pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)
            
            context!.translateBy(x: -point.x, y: -point.y)
            layer.render(in: context!)
            let 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.deallocate(capacity: 4)
            return color
        }
    }
    

    How to use

    override func touchesBegan(_ touches: Set, with event: UIEvent?) {
        let touch = touches.first
        if let point = touch?.location(in: view) {
            let color = myUIImageView.getPixelColorAt(point: point)
            print(color)
        }
    }
    

提交回复
热议问题