Swift on OS X:如何访问当前CGContext进行绘制 - [NSView drawRect:] [英] Swift on OS X: How to access the current CGContext for drawing in -[NSView drawRect:]

查看:678
本文介绍了Swift on OS X:如何访问当前CGContext进行绘制 - [NSView drawRect:]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Xcode 6.1

OS X 10.9.5

Swift Mac 基于文档的应用目标

Xcode 6.1
OS X 10.9.5
Swift Mac Document-based Application target

我使用 Swift 一个Cocoa Mac 应用程式( NOT iOS !)。我有一个自定义的 NSView 子类。我想覆盖 -drawRect:,并访问当前的 CGContext 使用CoreGraphics API做一些绘图。

I am using Swift to make a Cocoa Mac app (NOT iOS!). I have a custom NSView subclass. I'd like to override -drawRect:, and access the current CGContext to do some drawing using the CoreGraphics APIs.

但是,我似乎无法访问当前的 CGContext times)。这里是我的代码:

However, I can't seem to access the current CGContext in Swift (something I've done hundreds of times in ObjC). Here's my code:

import Cocoa

class Canvas: NSView {
    override func drawRect(dirtyRect: CGRect) {
        if let ctx: CGContext! = NSGraphicsContext.currentContext()?.CGContext {
            // do drawing
        }
    }
}

当我运行时,我的 drawRect 实现的第一行立即崩溃:

When I run, I get an immediate crash on the first line of my drawRect implementation:

-[NSWindowGraphicsContext CGContext]: unrecognized selector sent to instance 0x60800005e840

我做错了什么?如何获取当前 CGContext 以绘制Swift?

What am I doing wrong? How do I fetch the current CGContext for drawing in Swift?

我肯定要使用CoreGraphics API。除非在Swift中使用CoreGraphics API是完全不可能的,请不要回复有关如何使用AppKit绘图API的建议(我不在乎,如果他们更容易)。我想知道如何在OS X上使用Swift的CoreGraphics。

I definitely want to use the CoreGraphics API. Unless using the CoreGraphics API in Swift is entirely impossible, please do not respond with suggestions on how to use AppKit drawing APIs instead (I don't care if they are easier). I want to know how to use CoreGraphics from Swift on OS X.

推荐答案

不幸的是, CGContext 仅在10.10+中可用。还有 graphicsPort ,但它有类型 UnsafeMutablePointer (并且可能必须有些争执, code> CGContext ),并在10.10中弃用。

Unfortunately, CGContext is only available in 10.10+. There’s also graphicsPort, but it has type UnsafeMutablePointer<Void> (and presumably must be wrangled somewhat to recover a viable CGContext), and it’s deprecated in 10.10.

如果这似乎不可行,可以创建一个位图上下文使用 CGBitmapContextCreate 并吸收;那么您可以从中检索一个图像,并绘制它来查看结果。

If that doesn’t seem viable, you could create a bitmap context using CGBitmapContextCreate and draw into that; then you can retrieve an image from it and draw that to see the results.

这篇关于Swift on OS X:如何访问当前CGContext进行绘制 - [NSView drawRect:]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆