我正在使用下面的代码从UILabel类创建图像并将其存储在文档目录中。我想在macOS中实现相同的目的,但没有找到任何东西,我也从未在macOS App环境中进行过编程。在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)
}
}
}
最佳答案
可以使用.dataWithPDF(inside:)
将任何NSView子类呈现为图像。尝试这个:
let dataOfView = nameLabel.dataWithPDF(inside: nameLabel.bounds)
let imageOfView = NSImage(data: dataOfView)