【发布时间】: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