我有一个NSPopUpButton包含颜色列表的。在颜色标题前面,我需要显示一个相同颜色的小框(可能是相同颜色的图像)。所以,我在想,如果我可以创建一个NSImageusing NSColor(它已经存在),那么我可以使用该-[NSMenuItem setImage:]方法在弹出按钮的颜色标题前面显示图像。
那么,如何创建NSImageusing NSColor?
也欢迎任何其他解决问题的方法。:)
我有一个NSPopUpButton包含颜色列表的。在颜色标题前面,我需要显示一个相同颜色的小框(可能是相同颜色的图像)。所以,我在想,如果我可以创建一个NSImageusing NSColor(它已经存在),那么我可以使用该-[NSMenuItem setImage:]方法在弹出按钮的颜色标题前面显示图像。
那么,如何创建NSImageusing NSColor?
也欢迎任何其他解决问题的方法。:)
一个简单的类别方法将做到这一点
@interface NSImage (ImageAdditions)
+(NSImage *)swatchWithColor:(NSColor *)color size:(NSSize)size;
@end
@implementation NSImage (ImageAdditions)
+(NSImage *)swatchWithColor:(NSColor *)color size:(NSSize)size
{
    NSImage *image = [[[NSImage alloc] initWithSize:size] autorelease];
    [image lockFocus];
    [color drawSwatchInRect:NSMakeRect(0, 0, size.width, size.height)];
    [image unlockFocus];
   return image;    
}
@end
[编辑]删除不推荐使用的 API
如果您使用的是 AppKit,这里是其他答案的 Swift 5 便利初始化程序版本。可悲的是,这在 UIKit 中不起作用
extension NSImage {
    convenience init(color: NSColor, size: NSSize) {
        self.init(size: size)
        lockFocus()
        color.drawSwatch(in: NSRect(origin: .zero, size: size))
        unlockFocus()
    }
}
使用示例:
let redSwatchImage = NSImage(color: .red, size: NSSize(width: 128, height: 128))
根据需要随意更改语义
以及上面的快速扩展变体:
import Cocoa
extension NSImage {
  class func swatchWithColor(color: NSColor, size: NSSize) -> NSImage {
    let image = NSImage(size: size)
    image.lockFocus()
    color.drawSwatchInRect(NSRect(origin: .zero, size: size))
    image.unlockFocus()
    return image
  }
}
我非常想做这件事,所以我为它制作了一个小的 Swift 包:Swift Color Swatches。
它是这样使用的:
import ColorSwatches
// If you prefer to use a factory initializer on the image type:
let nsImagePurple1 = NSImage.swatch(color: .systemPurple)
let uiImagePurple1 = UIImage.swatch(color: .systemPurple)
// If you prefer to use an instance method on a color instance:
let nsImagePurple2 = NSColor.systemPurple.swatch()
let uiImagePurple2 = UIColor.systemPurple.swatch()
如果默认值不适合您,您也可以将大小传递给这些