ios - 在 macOS 编程中是否有 UIGraphicsGetImageFromCurrentImageContext() 的替代方法?

标签 ios swift macos core-graphics

我正在使用下面的代码从 UILabel 类创建图像并将它们存储在文档目录中。我想在 macOS 中实现同样的事情,但没有找到任何东西,我也从未在 macOS 应用程序环境中编程过。在 macOS 应用程序中,我尝试使用 CGDisplayCreateImage() 截取部分屏幕截图,但结果不符合预期。所以我想做的是创建标签并将其作为图像存储在 macOS 应用程序的本地存储中。

class func imageWith(name: String?) {
    //sizes = [Int]
    sizes.forEach { (value) in
        let frame = CGRect(x: 0, y: 0, width: value, height: value)
        let nameLabel = UILabel(frame: frame)
        nameLabel.textAlignment = .center
        nameLabel.backgroundColor = .black
        nameLabel.textColor = .white
        var fontSize = 25
        if value == 120 {
            fontSize = 50
        } else if value == 180 {
            fontSize = 60
        }
        nameLabel.font = UIFont.boldSystemFont(ofSize: CGFloat(fontSize))
        nameLabel.text = String(name?.prefix(2) ?? "Aa")

        //logic i wanted to port to macos
        UIGraphicsBeginImageContext(frame.size)
        if let currentContext = UIGraphicsGetCurrentContext() {
            nameLabel.layer.render(in: currentContext)
            let nameImage = UIGraphicsGetImageFromCurrentImageContext()

            //function which will save images to documents directory
            saveImageToDocumentDirectory(image: nameImage, name: name ?? "dummy", value: value)
        }
    }
}

最佳答案

任何 NSView 子类都可以使用 .dataWithPDF(inside:) 呈现为图像。试试这个:

let dataOfView = nameLabel.dataWithPDF(inside: nameLabel.bounds)
let imageOfView = NSImage(data: dataOfView)

关于ios - 在 macOS 编程中是否有 UIGraphicsGetImageFromCurrentImageContext() 的替代方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57238354/

相关文章:

Mac 上多个存储库的 Git 状态

ios - 不能为collectionView注册reuseIdentifier,为什么?

ios - 我在哪里更改 xcode 中的版本号

javascript - 如何将 Phaser 游戏上架 iOS App Store?

SwiftUI - 更改 TabBar 图标颜色

Swift UITapGestureRecognizer 未按预期工作

objective-c - 事件处理程序中的 NULL 属性(cocoa 应用程序)

ios - UITableView push segue 触发多次

swift - 如何添加 "Add Button"- 按钮

regex - 如何在 unix (osx) 中搜索/替换一堆文本文件