我有一个大图像和一个较小的图像,都是
Data
类型,我将其转换为 NSImage
。我想将较小的图像放在大图像的顶部,左上对齐,在一个新的单个NSImage
中。
目前此代码可以运行,但是
lockFocus
和 unlockFocus
均已弃用。我认为文档不够清晰,无法让我理解应该如何重写它。
这是工作代码:
func combineImages(image1: NSImage, image2: NSImage) -> NSImage {
let size = NSMakeSize(max(image1.size.width, image2.size.width), max(image1.size.height, image2.size.height))
let newImage = NSImage(size: size)
newImage.lockFocus()
image2.draw(at: NSPoint(x: 0, y: size.height - image2.size.height), from: NSZeroRect, operation: .sourceOver, fraction: 1.0)
image1.draw(at: NSZeroPoint, from: NSZeroRect, operation: .sourceOver, fraction: 1.0)
newImage.unlockFocus()
return newImage
}
弃用方法为:
此方法与分辨率无关的绘图不兼容 不应该使用。
您可以使用
init(size:flipped:drawingHandler:)
代替:
func combineImages(image1: NSImage, image2: NSImage) -> NSImage {
let size = NSSize(width: max(image1.size.width, image2.size.width), height: max(image1.size.height, image2.size.height))
let newImage = NSImage(size: size, flipped: false) { rect -> Bool in
let drawPointImage2 = NSPoint(x: 0, y: size.height - image2.size.height)
image2.draw(at: drawPointImage2, from: NSRect(origin: .zero, size: image2.size), operation: .sourceOver, fraction: 1.0)
image1.draw(at: NSPoint.zero, from: NSRect(origin: .zero, size: image1.size), operation: .sourceOver, fraction: 1.0)
return true
}
return newImage
}