【问题标题】:Draw text at 90 degree on NSImage在 NSImage 上以 90 度角绘制文本
【发布时间】:2020-08-20 06:54:22
【问题描述】:

我有以下代码在图像上绘制文本。如何绘制倾斜 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)

【问题讨论】:

标签: swift macos nsimage


【解决方案1】:

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

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()
        }
    }
}

【讨论】:

  • 谢谢...如何以同样的方式在右侧绘制文本?
  • 为了实现右侧放置,我更改了平移 x 坐标,但这会产生不需要的间距。请参阅stackoverflow.com/questions/61676256/…
【解决方案2】:

我找到了一个不错的简单方法 - 但您将不得不稍微调整一下坐标。变换将原点移动到左下角

大部分答案来自较早的答案 - How to rotate text in 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)

    }

这是我的输出

【讨论】:

  • 我赞成你的答案.. 但另一个答案似乎更简单。我会接受。谢谢你的帮助
  • 很乐意提供帮助 - 另一个答案为您提供了更多选择 :-)
猜你喜欢
  • 1970-01-01
  • 2012-12-02
  • 2018-04-02
  • 1970-01-01
  • 2022-11-14
  • 2011-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多