在Swift中获取点的颜色

时间:2015-01-02 17:37:54

标签: ios xcode object swift cgcontextref

我找到了一个Objective-C代码示例,它在这里得到一个像素的颜色: How to get the pixel color on touch?

我需要帮助的特定代码部分是使用CGColorSpaceCreateDeviceRGB创建上下文的地方:

---这是Objective-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);

我最好的尝试看起来如下(我还没有回复任何东西,我试图先正确地获取上下文):

---这是我在Swift转换中的最佳尝试

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'

如果您可以建议我如何调整上面的代码以正确输入上下文函数参数,我将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:5)

有两个不同的问题:

所以这应该编译:

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)