一個swift'ified版本的ivanzoid的回答
斯威夫特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
}
}
夫特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
}
}
基於底層CALayer
周圍,但容易翻譯回UIView
。
您是否找到(快速)解決方案? – CodeAndCats 2009-10-11 01:42:42
使用位圖上下文的速度足以達到我的目的。試試看看它是如何爲你工作的。 – 0x90 2009-10-15 02:03:15