我正在尝试将此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];
到目前为止,我最终得到了这个:
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)
问题在于CGBitmapContextCreate
返回CGContext
类型,NSGraphicsContext
初始化程序接受graphicsPort
作为CMutableVoidPointer
类型。那么如何将CGContext
转换为CMutableVoidPointer
?
这里有相关的反向型铸造,但它对我没有太大帮助 How to convert COpaquePointer in swift to some type (CGContext? in particular)
答案 0 :(得分:2)
我最终使用reinterpretCast
函数返回Int
地址的中间bitmapContext
变量。
var bitmapContext: CGContext = CGBitmapContextCreate(...)
let bitmapContextAddress: Int = reinterpretCast(bitmapContext)
let bitmapContextPointer: CMutableVoidPointer = COpaquePointer(UnsafePointer<CGContext>(bitmapContextAddress))
let context = NSGraphicsContext(graphicsPort: bitmapContextPointer, flipped: false)
答案 1 :(得分:0)
陈述如下:
当函数声明为采用CMutableVoidPointer参数时, 对于任何类型,它都可以接受与CMutablePointer相同的操作数 类型。
从那以后,它应该像这样工作:
var p: CMutablePointer<CGContext> = &bitmapContext
NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithGraphicsPort:p flipped:NO];
实际上,您应该能够将&bitmapContext
直接传递给CMutableVoidPointer
参数。