Agg*_*sor 2 xcode object ios cgcontextref swift
我找到了一个Objective-C代码示例,它可以在这里得到一个像素的颜色: 如何在触摸时获得像素颜色?
我需要帮助的特定代码部分是使用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);
Run Code Online (Sandbox Code Playgroud)
我最好的尝试看起来如下(我没有返回任何东西,但我正试图先正确地获取上下文):
---这是我对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)
}
Run Code Online (Sandbox Code Playgroud)
但是这给了我一个错误
Cannot convert the expression's type '(UnsafeMutablePointer<CUnsignedChar>, width: IntegerLiteralConvertible, height: IntegerLiteralConvertible, bitsPerComponent: IntegerLiteralConvertible, bytesPerRow: IntegerLiteralConvertible, space: NilLiteralConvertible, bitmapInfo: CGImageAlphaInfo)' to type 'IntegerLiteralConvertible'
Run Code Online (Sandbox Code Playgroud)
如果您可以建议我如何调整上面的代码以正确输入上下文函数参数,我将不胜感激,谢谢!
有两个不同的问题:
CGBitmapContextCreate()是一个函数,而不是一个方法,因此默认情况下不使用外部参数名称.CGImageAlphaInfo.PremultipliedLast不能作为bitmapInfo:参数传递,比较Swift OpenGL未解析的标识符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)
Run Code Online (Sandbox Code Playgroud)
请注意,您应该为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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2920 次 |
| 最近记录: |