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