【问题标题】:Is there any alternative to UIGraphicsGetImageFromCurrentImageContext() in macOS programming?在 macOS 编程中是否有 UIGraphicsGetImageFromCurrentImageContext() 的替代方法?
【发布时间】:2019-07-28 06:00:40
【问题描述】:

我正在使用下面的代码从 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)
        }
    }
}

【问题讨论】:

  • 欢迎来到 SO。请编辑您的问题,发布您的尝试以及您面临的问题。
  • 请发布您尝试过的 macOS 代码,并更清楚地描述您得到的“不符合预期”的结果。

标签: ios swift macos core-graphics


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 2021-11-06
    • 2023-03-21
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多