首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将NSGradient绘制为NSImage?

如何将NSGradient绘制为NSImage?
EN

Stack Overflow用户
提问于 2014-06-10 13:00:32
回答 2查看 1.1K关注 0票数 1

我正在尝试将NSGradient保存为RubyMotion中的图像,但我无法让它正常工作。这是我到目前为止掌握的代码:

代码语言:javascript
复制
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)

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-06-10 13:26:53

我不知道RubyMotion,但在目标C中如何做到这一点:

代码语言:javascript
复制
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];
票数 6
EN

Stack Overflow用户

发布于 2019-11-10 11:58:06

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

代码语言:javascript
复制
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()
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24141664

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档