在NSImage上以90度绘制文字。

问题描述 投票:0回答:2

我有下面的代码在图片上绘制文字,我如何绘制90度倾斜的文字?

let textStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
        let textFontAttributes = [
            NSAttributedStringKey.font: font,
            NSAttributedStringKey.foregroundColor: textcolor,
            NSAttributedStringKey.paragraphStyle: textStyle

        ]
text.draw(in: textRect, withAttributes: textFontAttributes)

enter image description here

swift macos nsimage
2个回答
1
投票

这里是演示的方法与可计算的位置。

demo

class DemoView: NSView {
    override func draw(_ rect: NSRect) {

        // .. your drawing code here

        NSColor.red.set()  // just for demo
        rect.fill()        // just for demo

        if let context = NSGraphicsContext.current?.cgContext {
            context.saveGState()

            let text: NSString = "Hello World"
            let attributes = [
                NSAttributedString.Key.foregroundColor: NSColor.white, 
                NSAttributedString.Key.font: NSFont.systemFont(ofSize: 24)
            ]

            let size = text.size(withAttributes: attributes)
            context.translateBy(x: size.height, y: (rect.height - size.width) / 2)
            context.rotate(by: CGFloat.pi / 2)

            text.draw(at: .zero, withAttributes: attributes)

            context.restoreGState()
        }
    }
}

1
投票

我发现了一个很好的简单方法--但你必须稍微玩一下坐标。 变换将原点移动到左下角。

大部分的答案来自于之前的一个答案--------。如何在NSView中旋转文本?(Mac OS, Cocoa, Swift)但它需要更新一下。

    override func draw(_ dirtyRect: NSRect) {
    super.draw(dirtyRect)

    let font = NSFont.boldSystemFont(ofSize: 18)
    let textStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
    let textFontAttributes = [
        NSAttributedString.Key.font: font,
        NSAttributedString.Key.foregroundColor: NSColor.red,
        NSAttributedString.Key.paragraphStyle: textStyle
    ]

    let textRect = CGRect(x: 200, y: 200   , width: 200, height: 100)
    "normal".draw(in: textRect, withAttributes: textFontAttributes)

    let transf : NSAffineTransform = NSAffineTransform()
    transf.rotate(byDegrees: 90)
    transf.concat()
    "200, -100".draw(at: NSMakePoint(200, -100), withAttributes:textFontAttributes)
    "300, -50".draw(at: NSMakePoint(300, -50), withAttributes:textFontAttributes)

    }

这是我的输出rotated text

© www.soinside.com 2019 - 2024. All rights reserved.