Created
April 29, 2022 11:08
-
-
Save vladimir-anisimov/59c448b2a7503dec67a89c0328446bc2 to your computer and use it in GitHub Desktop.
Color of point in UIView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension UIView { | |
func colorOfPoint(point: CGPoint) -> UIColor { | |
let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceRGB() | |
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue) | |
var pixelData: [UInt8] = [0, 0, 0, 0] | |
guard let context = CGContext(data: &pixelData, | |
width: 1, | |
height: 1, | |
bitsPerComponent: 8, | |
bytesPerRow: 4, | |
space: colorSpace, | |
bitmapInfo: bitmapInfo.rawValue) else { | |
return .white | |
} | |
context.translateBy(x: -point.x, y: -point.y) | |
self.layer.render(in: context) | |
let red: CGFloat = CGFloat(pixelData[0]) / CGFloat(255.0) | |
let green: CGFloat = CGFloat(pixelData[1]) / CGFloat(255.0) | |
let blue: CGFloat = CGFloat(pixelData[2]) / CGFloat(255.0) | |
let alpha: CGFloat = CGFloat(pixelData[3]) / CGFloat(255.0) | |
let color: UIColor = UIColor(red: red, green: green, blue: blue, alpha: alpha) | |
return color | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment