【问题标题】:Get Color Of Pixel At Point In Swift在Swift中获取像素点的颜色
【发布时间】:2015-01-02 17:37:53
【问题描述】:

我在这里找到了一个获取像素颜色的 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'

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

【问题讨论】:

    标签: ios xcode object swift cgcontextref


    【解决方案1】:

    有两个不同的问题:

    所以这应该编译:

    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)
    

    【讨论】:

    • 哇!我从来不知道函数和方法之间有任何这样的区别(它们总是意味着同样的事情),这真的很清楚,谢谢。还要感谢您指出分配差异,我已经坚持了一段时间。非常感谢!
    猜你喜欢
    • 2020-05-31
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    • 2011-11-30
    相关资源
    最近更新 更多