Skip to content

Instantly share code, notes, and snippets.

@mkuliszkiewicz
Last active May 28, 2023 13:22
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mkuliszkiewicz/940677042f5f293caf57 to your computer and use it in GitHub Desktop.
Save mkuliszkiewicz/940677042f5f293caf57 to your computer and use it in GitHub Desktop.
UIView extension which allows to get colour of any point inside
//
// 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
}
}
@cstad
Copy link

cstad commented Dec 22, 2014

What are the license terms of your code?

@VictorZhang2014
Copy link

I ran the code below on Swift 5 that is working very well. Thank you blogger!

    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