gpt4 book ai didi

ios - 在 Swift 中获取像素点的颜色

转载 作者:可可西里 更新时间:2023-11-01 00:38:00 26 4
gpt4 key购买 nike

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

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

最佳答案

有两个不同的问题:

所以这应该编译:

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)

关于ios - 在 Swift 中获取像素点的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27746185/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com