Created
December 15, 2020 14:14
-
-
Save VictorZhang2014/09556c6c51e435d2d7481aab161bba35 to your computer and use it in GitHub Desktop.
Get color from point, you specify a CGPoint, the function returns that point as a UIColor to you. - Swift 5.2
This file contains 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 getColourFromPoint(point:CGPoint) -> UIColor { | |
let colorSpace:CGColorSpace = CGColorSpaceCreateDeviceRGB() | |
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue) | |
var pixelData:[UInt8] = [0, 0, 0, 0] | |
let context = CGContext(data: &pixelData, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) | |
context?.translateBy(x: -point.x, y: -point.y) | |
if let _context = context { | |
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) | |
return UIColor(red: red, green: green, blue: blue, alpha: alpha) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment