【发布时间】:2021-02-18 22:02:35
【问题描述】:
我已经看到了一些关于如何使用字符串How to generate an UIImage from custom text in Swift 生成 UIImage 的解决方案,但是在 macOS 上复制相同的东西似乎很困难,因为它们的图形库不同。请我只需要将一个字符串转换为 NSImage 以便我可以在 mac 应用程序上使用它。
【问题讨论】:
我已经看到了一些关于如何使用字符串How to generate an UIImage from custom text in Swift 生成 UIImage 的解决方案,但是在 macOS 上复制相同的东西似乎很困难,因为它们的图形库不同。请我只需要将一个字符串转换为 NSImage 以便我可以在 mac 应用程序上使用它。
【问题讨论】:
你只需要创建一个新的 NSImage 对象,lockFocus,在其上绘制属性字符串并再次 unlockFocus:
extension NSAttributedString {
func image(foregroundColor: NSColor? = nil, backgroundColor: NSColor? = nil) -> NSImage {
let size = self.size()
let image = NSImage(size: size)
image.lockFocus()
let mutableStr = NSMutableAttributedString(attributedString: self)
if let foregroundColor = foregroundColor,
let backgroundColor = backgroundColor {
mutableStr.setAttributes([.foregroundColor: foregroundColor,
.backgroundColor: backgroundColor],
range: .init(location: 0, length: length))
}
else
if let foregroundColor = foregroundColor {
mutableStr.setAttributes([.foregroundColor: foregroundColor],
range: .init(location: 0, length: length))
}
else
if let backgroundColor = backgroundColor {
mutableStr.setAttributes([.backgroundColor: backgroundColor],
range: .init(location: 0, length: length))
}
mutableStr.draw(in: .init(origin: .zero, size: size))
image.unlockFocus()
return image
}
}
let stackOverflow = NSAttributedString(string: "StackOverflow")
stackOverflow.image()
stackOverflow.image(foregroundColor: .red)
stackOverflow.image(backgroundColor: .white)
stackOverflow.image(foregroundColor: .red, backgroundColor: .green)
extension StringProtocol {
func image(foregroundColor: NSColor? = nil, backgroundColor: NSColor? = nil) -> NSImage {
NSAttributedString(string: .init(self)).image(foregroundColor: foregroundColor, backgroundColor: backgroundColor)
}
}
"StackOverflow".image()
编辑/更新:
如果您想从标签创建图像(NSTextField)
extension NSView {
var image: NSImage? {
guard let bitmapImageRep = bitmapImageRepForCachingDisplay(in: bounds) else { return nil }
cacheDisplay(in: bounds, to: bitmapImageRep)
guard let cgImage = bitmapImageRep.cgImage else { return nil }
return NSImage(cgImage: cgImage, size: bounds.size)
}
}
let label = NSTextField(labelWithString: "StackOverflow")
label.textColor = .blue
label.backgroundColor = .clear
label.sizeToFit()
label.image
【讨论】: