【问题标题】:How do I draw NSGradient to NSImage?如何将 NSGradient 绘制到 NSImage?
【发布时间】:2014-06-10 13:00:32
【问题描述】:

我正在尝试获取 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


    【解决方案1】:

    我不知道 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];
    

    【讨论】:

    • 这对我来说效果很好。诀窍是 NSBitmapImageRep.alloc.initWithFocusedViewRect(rect)。
    【解决方案2】:

    如果你想知道它在 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()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多