首页 文章

使用Swift将文本添加到CGContext

提问于
浏览
0

我在macOS上使用Swift 3 / Xcode 8 .

我在NSView中覆盖 draw ,使用当前上下文,我能够绘制简单的形状(请参阅代码):

class sample:NSImageView {

override func draw(_ dirtyRect: NSRect) {
    super.draw(dirtyRect)
    let context = NSGraphicsContext.current()?.cgContext;
    let length = CGPoint(x: 100, y: 100)
    let p1 = CGPoint(x: 200, y: 200)
    let shape = "square"


    context!.beginPath()
    context!.move(to: p1)

    if shape == "line" {
        let pointEnd = CGPoint(x: p1.x + length.x, y: p1.y + length.y)
        context!.addLine(to: pointEnd)
    } else if shape == "square" {
        let p2 = CGPoint(x: p1.x + length.x, y: p1.y)
        let p3 = CGPoint(x: p1.x + length.x, y: p1.y + length.y)
        let p4 = CGPoint(x: p1.x, y: p1.y + length.y)
        context!.addLine(to: p2)
        context!.addLine(to: p3)
        context!.addLine(to: p4)
        context!.addLine(to: p1)
    }

    context!.setStrokeColor(red: 1, green: 1, blue: 1, alpha: 1.0)
    context!.setFillColor(red: 0, green: 1, blue: 0, alpha: 1)
    context!.setLineWidth(2.0)
    context!.strokePath()

    let textColor = NSColor(calibratedRed: 1, green: 1, blue: 1, alpha: 1.0)
    let textColorB = NSColor(calibratedRed: 1, green: 1, blue: 1, alpha: 0.0)
    let rect = CGRect(x: 200, y: 200, width: 30, height: 130)
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = .center
    let attr = [NSParagraphStyleAttributeName: paragraphStyle, NSForegroundColorAttributeName: textColor, NSBackgroundColorAttributeName: textColorB, NSFontAttributeName:NSFont.init(name: "HelveticaNeue-Thin", size: 14)]

    let q: NSString = "hello, world"
    let center = CGPoint(x: 0, y: 0)
    q.draw(at: center, withAttributes: attr)                                                                 
}

The above is corrected to show the entire method.

This works as expected except for the text draw. Two draws I tried are shown in the last 2 lines. The first is as suggested below and it crashes (see message in comment for that line). The second is close but it demands an NSDrawingContext, not a CGContext.

我还想画一些文字(比如说在线下) . 我做了很多搜索,发现没有任何效果 . CGContexts似乎有与绘制文本相关的方法,但似乎没有实际绘制它 . 要清楚,我发现没有任何东西可以编译,更不用说了 .

注意:我是macOS开发的新手(虽然做了一些iOS) . 所以我可能会遗漏一些非常明显的东西 .

The problem was in the color assignment in the attributes. Edited with code that now works.

1 回答

  • 2

    将文本绘制到当前图形上下文的简单方法是使用NSString的draw(at:withAttributes:) .

    例:

    class MyView : NSView {
        override func draw(_ dirtyRect: NSRect) {
            let atts = [NSFontAttributeName:NSFont.init(name: "Georgia", size: 30)]
            ("Hello world" as NSString).draw(
                 at: NSMakePoint(100,100), 
                 withAttributes: atts)
        }
    }
    

    结果:

    enter image description here

相关问题