如何将 NSGradient 绘制到 NSImage?

Rya*_*vre 0 macos nsimage nsgradient rubymotion

我正在尝试使用 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)
Run Code Online (Sandbox Code Playgroud)

它运行没有错误,但保存的文件是空白的,没有图像数据。任何人都可以帮助我指出正确的方向吗?

cod*_*ine 5

我不知道 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];
Run Code Online (Sandbox Code Playgroud)