Una versione swift'ified di ivanzoid 's risposta
Swift 3
extension CALayer {
func colorOfPoint(point:CGPoint) -> CGColor {
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.render(in: context!)
let red: CGFloat = CGFloat(pixel[0])/255.0
let green: CGFloat = CGFloat(pixel[1])/255.0
let blue: CGFloat = CGFloat(pixel[2])/255.0
let alpha: CGFloat = CGFloat(pixel[3])/255.0
let color = UIColor(red:red, green: green, blue:blue, alpha:alpha)
return color.cgColor
}
}
Swift 2
extension CALayer {
func colorOfPoint(point:CGPoint)->CGColorRef
{
var pixel:[CUnsignedChar] = [0,0,0,0]
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)
let context = CGBitmapContextCreate(&pixel, 1, 1, 8, 4, colorSpace, bitmapInfo.rawValue)
CGContextTranslateCTM(context, -point.x, -point.y)
self.renderInContext(context!)
let red:CGFloat = CGFloat(pixel[0])/255.0
let green:CGFloat = CGFloat(pixel[1])/255.0
let blue:CGFloat = CGFloat(pixel[2])/255.0
let alpha:CGFloat = CGFloat(pixel[3])/255.0
let color = UIColor(red:red, green: green, blue:blue, alpha:alpha)
return color.CGColor
}
}
basata soprattutto sottostante CALayer
ma facilmente traducibile ritorna UIView
.
fonte
2014-11-15 11:59:20
Hai trovato una soluzione (veloce)? – CodeAndCats
L'utilizzo del contesto bitmap si è rivelato abbastanza veloce per i miei scopi. Fare un tentativo e vedere come funziona per voi. – 0x90