是否可以从字符串生成 NSImage?

Is it possible to generate NSImage from string?

我看过几个关于如何使用字符串 生成 UIImage 的解决方案,但是在 macOS 上复制相同的东西似乎很困难,因为它们的图形库不同.请我只需要将字符串转换为 NSImage,这样我就可以在 mac 应用程序中使用它。

您只需要创建一个新的 NSImage 对象,lockFocus,在其上绘制属性字符串并再次解锁:

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 Whosebug = NSAttributedString(string: "Whosebug")
Whosebug.image()
Whosebug.image(foregroundColor: .red)
Whosebug.image(backgroundColor: .white)
Whosebug.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)
    }
}

"Whosebug".image()

edit/update:

如果您想从标签 (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: "Whosebug")
label.textColor = .blue
label.backgroundColor = .clear
label.sizeToFit()
label.image