我正在尝试将一个图像绘制到另一个图像上,然后将该合成图像输出为图像文件。该方法在我第一次调用时工作正常但任何后续调用在最后一个复合上层叠另一个图像。即它保持分层而不是获得新的背景图像。
我希望我已经明确表示(有点难以解释),我们将非常感谢任何帮助。
-(NSImage *)compositeImage:(NSImage *)overlay Onto:(NSImage *)background AtPoint:(NSPoint)location{
NSImage *returnImage;
[background lockFocus];
[[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
[overlay drawInRect:NSMakeRect(location.x, location.y, [overlay size].width, [overlay size].width) fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
[background unlockFocus];
returnImage = background;
return returnImage;
}
答案 0 :(得分:1)
您应该在绘制之前复制图像,这样就不会更改原始图像。
-(NSImage *)compositeImage:(NSImage *)overlay Onto:(NSImage *)background AtPoint:(NSPoint)location{
NSImage * backgroundCopy = [background copy];
[backgroundCopy lockFocus];
[[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
[overlay drawInRect:NSMakeRect(location.x, location.y, [overlay size].width, [overlay size].width) fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
[backgroundCopy unlockFocus];
return backgroundCopy; //release this object in calling function.
}
答案 1 :(得分:0)
Parag Bafna在Swift 3中的回答
func draw(image: NSImage, onto backgroundImage: NSImage) -> NSImage? {
guard let canvas = backgroundImage.copy() as? NSImage else {
return nil
}
canvas.lockFocus()
NSGraphicsContext.current()?.imageInterpolation = NSImageInterpolation.high
image.draw(at: .zero,
from: NSRect(origin: .zero, size: backgroundImage.size),
operation: .sourceOver,
fraction: 1.0)
canvas.unlockFocus()
return canvas
}