我正在尝试在 Cocoa(不是 UIKit)中使用 Swift 从 ttf 字体生成 NSImage,目前我正在努力创建上下文。
我的基本代码来自这个项目:https ://github.com/reeonce/Ionicons.swift 但它是为 UIKit 设计的,所以我尝试为 Cocoa 翻译它。
这是原始代码:
extension UIImage {
public class func imageWithIonIcon(icon: Ionicons, height: CGFloat, color: UIColor) -> UIImage {
let font = UIFont(name: "ionicons", size: height)!
let iconSize = (icon.rawValue as NSString).sizeWithAttributes([NSFontAttributeName: font])
UIGraphicsBeginImageContextWithOptions(iconSize, false, 0.0)
(icon.rawValue as NSString).drawAtPoint(CGPointZero, withAttributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: color])
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
这是我目前所拥有的:
extension NSImage {
public class func imageWithIonIcon(icon: Ionicons, height: CGFloat, color: NSColor) -> NSImage? {
if let font = NSFont(name: "Ionicons", size: height) {
let iconSize = (icon.rawValue as NSString).sizeWithAttributes([NSFontAttributeName: font])
let context = CGBitmapContextCreate(nil, Int(iconSize.width), Int(iconSize.height), 8, Int(iconSize.width)*8, CGColorSpaceCreateDeviceRGB(), nil)
(icon.rawValue as NSString).drawAtPoint(CGPointZero, withAttributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: color])
let image = NSImage(CGImage: CGBitmapContextCreateImage(context), size: iconSize)
return image
}
return nil
}
}
这给了我一个运行时错误,因为我不知道如何初始化上下文:
<Error>: CGBitmapContextCreate: unsupported parameter combination: 8 integer bits/component; 24 bits/pixel; 3-component color space; kCGImageAlphaNone; 168 bytes/row.
对初学者有什么提示吗?谢谢