【问题标题】:MacOS: Add a text overlay to an image in SwiftMacOS:在 Swift 中为图像添加文本覆盖
【发布时间】:2019-01-30 22:19:07
【问题描述】:

我为 UIImage 写了一个小扩展,它在图像中添加了一个文本:

extension UIImage {

    func addTextToImage(textToAdd: String) -> UIImage {
        let textColor = UIColor.white
        let textFont = UIFont(name: "Snell Roundhand", size: 40)!
        let scale = UIScreen.main.scale
        UIGraphicsBeginImageContextWithOptions(self.size, false, scale)

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = NSTextAlignment.center

        var textFontAttributes = [
            NSAttributedString.Key.font: textFont,
            NSAttributedString.Key.foregroundColor: textColor,
            NSAttributedString.Key.paragraphStyle: paragraphStyle
            ] as [NSAttributedString.Key : Any]


        self.draw(in: CGRect(origin: CGPoint.zero, size: self.size))
        let textFrame = CGPoint(x: self.size.width/4, y: self.size.height/4)
        let rect = CGRect(origin: textFrame, size: CGSize(width: self.size.width/2, height: self.size.height/2) )
        text.draw(in: rect, withAttributes: textFontAttributes)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage!
    }
}

结果应如下所示:

现在我想为 NSImage 在 MacOS 上运行做同样的事情。

任何想法如何做到这一点?

Stackoverflow 上的所有类似问题要么很老,没有答案,要么在 Objective C 中

【问题讨论】:

  • “Stackoverflow 上的所有类似问题都是 [...] 或 Objective C 中的” API 基本相同。
  • 我找到答案的唯一问题是这个:stackoverflow.com/questions/27790315/…
  • 它已经 4 岁了,在 cmets 中他们正在讨论使用旧 API。

标签: swift macos uikit core-graphics


【解决方案1】:

找到解决办法:

extension NSImage {

    func addTextToImage(drawText text: String) -> NSImage {

        let targetImage = NSImage(size: self.size, flipped: false) { (dstRect: CGRect) -> Bool in

            self.draw(in: dstRect)
            let textColor = NSColor.white
            let textFont = NSFont(name: "Snell Roundhand", size: 36)! //Helvetica Bold
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.alignment = NSTextAlignment.center

            var textFontAttributes = [
                NSAttributedString.Key.font: textFont,
                NSAttributedString.Key.foregroundColor: textColor,
                ] as [NSAttributedString.Key : Any]

            let textOrigin = CGPoint(x: self.size.height/3, y: -self.size.width/4)
            let rect = CGRect(origin: textOrigin, size: self.size)
            text.draw(in: rect, withAttributes: textFontAttributes)
            return true
        }
        return targetImage
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    相关资源
    最近更新 更多