获取 Swift 点的像素颜色

Get Color Of Pixel At Point In Swift

我在此处找到了一个 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'

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

有两个不同的问题:

  • 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 个字节分配 space,而不是 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)