如何在swift中将COpaquePointer转换为某种类型(特别是CGContext?)

 QFWQF2010_899 发布于 2023-01-12 02:02

我在swift中有以下代码,不能编译:

class CustomView: NSView {
  override func drawRect(dirtyRect: NSRect) {
    var contextPointer: COpaquePointer = NSGraphicsContext.currentContext()!.graphicsPort()
    var context: CGContext? = contextPointer as? CGContext
    CGContextSetRGBFillColor(context, 1, 0, 0, 1)
    CGContextFillRect(context, CGRectMake(0, 0, 100, 100))
    CGContextFlush(context)
  }
}

如何将COpaquePointer转换为CGContext?

2 个回答
  • 截至开发者预览版5,NSGraphicsContext现在有一个CGContext属性.它还没有记录,但它在头文件中:

    @property (readonly) CGContextRef CGContext NS_RETURNS_INNER_POINTER NS_AVAILABLE_MAC(10_10);
    

    2023-01-12 02:17 回答
  • 这有点难看; 如果更新了graphicsPort()方法以直接返回CGContextRef(例如UIGraphicsGetCurrentContext()),而不是void*,那会更好.我添加了这个扩展名,NSGraphicsContext以便现在将它扫到地毯下:

    extension NSGraphicsContext {
      var cgcontext: CGContext {
        return Unmanaged<CGContext>.fromOpaque(self.graphicsPort()).takeUnretainedValue()
      }
    }
    

    只需NSGraphicsContext.currentContext().cgcontext在任何需要CGContext的地方打电话.

    2023-01-12 02:24 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有