我如何将NSGradient绘制到NSImage?

问题描述 投票:0回答:2

我正在尝试获取NSGradient并将其另存为RubyMotion中的图像,但是我无法使其正常工作。这是我到目前为止的代码:

gradient = NSGradient.alloc.initWithColors(colors, 
  atLocations: locations.to_pointer(:double), 
  colorSpace: NSColorSpace.genericRGBColorSpace
)

size = Size(width, height)
image = NSImage.imageWithSize(size, flipped: false, drawingHandler: lambda do |rect|
  gradient.drawInRect(rect, angle: angle)
  true
end)

data = image.TIFFRepresentation
data.writeToFile('output.tif', atomically: false)

它运行没有错误,但是保存的文件为空白,没有图像数据。谁能帮助我指出正确的方向?

macos rubymotion nsimage nsgradient
2个回答
4
投票

我不知道RubyMotion,但是在Objective-C中是这样的:

NSGradient *grad = [[NSGradient alloc] initWithStartingColor:[NSColor redColor]
                                                 endingColor:[NSColor blueColor]];

NSRect rect = CGRectMake(0.0, 0.0, 50.0, 50.0);
NSImage *image = [[NSImage alloc] initWithSize:rect.size];
NSBezierPath *path = [NSBezierPath bezierPathWithRect:rect];
[image lockFocus];
[grad drawInBezierPath:path angle:0.0];
NSBitmapImageRep *imgRep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:rect];
NSData *data = [imgRep representationUsingType:NSPNGFileType properties:nil];
[image unlockFocus];
[data writeToFile: @"/path/to/file.png" atomically:NO];

0
投票

如果您想知道它如何在Swift 5中工作:

extension NSImage {
    convenience init?(gradientColors: [NSColor], imageSize: NSSize) {
        guard let gradient = NSGradient(colors: gradientColors) else { return nil }
        let rect = NSRect(origin: CGPoint.zero, size: imageSize)
        self.init(size: rect.size)
        let path = NSBezierPath(rect: rect)
        self.lockFocus()
        gradient.draw(in: path, angle: 0.0)
        self.unlockFocus()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.