我发现了一个目标C代码的例子,它在这里获取像素的颜色:How to get the pixel color on touch?。
我需要帮助的代码的特定部分是使用CGColorSpaceCreateDeviceRGB创建上下文的位置:
-这就是目标-C代码
unsigned char pixel[4] = {0};
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(pixel,
1, 1, 8, 4, colorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedLast);
CGContextTranslateCTM(context, -point.x, -point.y);我最好的尝试如下(我还没有返回任何内容,我正在尝试首先正确地获取上下文):
-这是我最好的尝试
func getPixelColorAtPoint()
{
let pixel = UnsafeMutablePointer<CUnsignedChar>.alloc(1)
var colorSpace:CGColorSpaceRef = CGColorSpaceCreateDeviceRGB()
let context = CGBitmapContextCreate(pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: nil, bitmapInfo: CGImageAlphaInfo.PremultipliedLast)
}然而,这给了我一个错误。
Cannot convert the expression's type '(UnsafeMutablePointer<CUnsignedChar>, width: IntegerLiteralConvertible, height: IntegerLiteralConvertible, bitsPerComponent: IntegerLiteralConvertible, bytesPerRow: IntegerLiteralConvertible, space: NilLiteralConvertible, bitmapInfo: CGImageAlphaInfo)' to type 'IntegerLiteralConvertible'如果您能建议我如何修改上面的代码,以便正确地输入上下文函数参数,我将非常感谢您!
发布于 2015-01-02 17:53:34
有两个不同的问题:
CGBitmapContextCreate()是一个函数,而不是一个方法,因此默认情况下不使用外部参数名。CGImageAlphaInfo.PremultipliedLast不能作为bitmapInfo:参数传递,请比较Swift OpenGL unresolved identifier kCGImageAlphaPremultipliedLast。因此,这应该汇编如下:
let pixel = UnsafeMutablePointer<CUnsignedChar>.alloc(4)
var colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
let context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, bitmapInfo)
// ...
pixel.dealloc(4)注意,您应该为4个字节分配空间,而不是1字节。
另一种选择是:
var pixel : [UInt8] = [0, 0, 0, 0]
var colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
let context = CGBitmapContextCreate(UnsafeMutablePointer(pixel), 1, 1, 8, 4, colorSpace, bitmapInfo)https://stackoverflow.com/questions/27746185
复制相似问题