Method for fetching color of CGPoint from image in UIImageView :-

extension UIImageView {

    func getColorOfPoint(_ point:CGPoint)->UIColor
        {
            var pixel:[CUnsignedChar] = [0,0,0,0]
            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)
        
            self.layer.render(in: context!)
        
            let red:CGFloat = CGFloat(pixel[0])/FLOATCOLORDEVIDER
            let green:CGFloat = CGFloat(pixel[1])/FLOATCOLORDEVIDER
            let blue:CGFloat = CGFloat(pixel[2])/FLOATCOLORDEVIDER
            let alpha:CGFloat = CGFloat(pixel[3])/FLOATCOLORDEVIDER
        
            let color : UIColor = UIColor(red:red, green: green, blue:blue, alpha:alpha)
        
            return color
        }
   }

Ex :-

editingView.currentColor = imgColorPicker.getColorOfPoint(imgLastPoint)

You may also like

Leave a Reply