MacOS:在Swift中为图像添加文字叠加层 [英] MacOS: Add a text overlay to an image in Swift

查看:296
本文介绍了MacOS:在Swift中为图像添加文字叠加层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为UIImage编写了一个小扩展程序,该扩展程序向图像添加了文本:

I've written a small extension for UIImage, which adds a text to an image:

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上运行做同样的事情.

Now I want to do the same thing for NSImage to run on MacOS.

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

Any ideas how to do this?

关于Stackoverflow的所有类似问题都非常古老,无法回答或在Objective C中

All similar questions on Stackoverflow are either very old, unanswered or in Objective C

推荐答案

找到了解决方案:

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

这篇关于MacOS:在Swift中为图像添加文字叠加层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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