Last active
May 28, 2023 13:22
-
-
Save mkuliszkiewicz/940677042f5f293caf57 to your computer and use it in GitHub Desktop.
UIView extension which allows to get colour of any point inside
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
// | |
// UIView+GetColor.swift | |
// SwiftPick | |
// | |
// Created by Maciej Banasiewicz, Michał Apanowicz on 06/07/14. | |
// | |
// | |
import UIKit | |
extension UIView { | |
func getColourFromPoint(point:CGPoint) -> UIColor { | |
let colorSpace:CGColorSpace = CGColorSpaceCreateDeviceRGB() | |
let bitmapInfo = CGBitmapInfo.fromRaw(CGImageAlphaInfo.PremultipliedLast.toRaw())! | |
var pixelData:UInt8[] = [0, 0, 0, 0] | |
let context = CGBitmapContextCreate(&pixelData, 1, 1, 8, 4, colorSpace, bitmapInfo) | |
CGContextTranslateCTM(context, -point.x, -point.y); | |
self.layer.renderInContext(context) | |
var red:CGFloat = CGFloat(pixelData[0])/CGFloat(255.0) | |
var green:CGFloat = CGFloat(pixelData[1])/CGFloat(255.0) | |
var blue:CGFloat = CGFloat(pixelData[2])/CGFloat(255.0) | |
var alpha:CGFloat = CGFloat(pixelData[3])/CGFloat(255.0) | |
var 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
I ran the code below on Swift 5 that is working very well. Thank you blogger!