在Swift中将CFContextRef转换为可变的void指针?

che*_*bur 5 types pointers casting void swift

我正在尝试将此objc代码转换为swift:

CGContextRef contextRef = CGBitmapContextCreate(NULL,
                                                proposedRect.size.width,
                                                proposedRect.size.height,
                                                CGImageGetBitsPerComponent(imageRef),
                                                0,
                                                colorSpaceRef,
                                                (CGBitmapInfo)kCGImageAlphaPremultipliedFirst);
NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithGraphicsPort:contextRef flipped:NO];
Run Code Online (Sandbox Code Playgroud)

到目前为止,我最终得到了这个:

var bitmapContext: CGContext = CGBitmapContextCreate(data, UInt(proposedRect.width), UInt(proposedRect.height), CGImageGetBitsPerComponent(image), 0, colorSpace, CGBitmapInfo(CGImageAlphaInfo.PremultipliedFirst.toRaw()))
let context = NSGraphicsContext(graphicsPort: bitmapContext, flipped: false)
Run Code Online (Sandbox Code Playgroud)

问题是,CGBitmapContextCreate收益CGContext类型和NSGraphicsContext初始化参数graphicsPortCMutableVoidPointer类型.那我怎么转换CGContextCMutableVoidPointer

相关的反向类型转换在这里找到,但它没有提供太多帮助 如何将swpa中的COpaquePointer转换为某种类型(特别是CGContext?)

che*_*bur 2

我最终得到了reinterpretCast返回IntbitmapContext地址的中间变量的函数。

var bitmapContext: CGContext = CGBitmapContextCreate(...)

let bitmapContextAddress: Int = reinterpretCast(bitmapContext)
let bitmapContextPointer: CMutableVoidPointer = COpaquePointer(UnsafePointer<CGContext>(bitmapContextAddress))
let context = NSGraphicsContext(graphicsPort: bitmapContextPointer, flipped: false)
Run Code Online (Sandbox Code Playgroud)

  • 感谢你的回答!不过,我认为“reinterpretCast”已经从语言中消失了;你需要使用`unsafeBitCast`来代替。 (2认同)