我正在使用以下代码来调整图像大小(保持宽高比)。当我尝试将大小为2432X3648像素的图像调整为1800X2700像素时,输出图像的原点会发生偏移。
请查看调整大小后的示例图像。我已标记图像。调整大小的代码在其他情况下似乎运行良好。请给予建议。
extension NSImage {
func resizeTo(width: CGFloat, height: CGFloat) -> NSImage {
let ratioX = width / size.width
let ratioY = height / size.height
var ratio = ratioX < ratioY ? ratioX : ratioY
let newHeight = size.height * ratio
let newWidth = size.width * ratio
let canvasSize = CGSize(width: newWidth, height: newHeight)
let img = NSImage(size: canvasSize)
img.lockFocus()
let context = NSGraphicsContext.current()
context?.imageInterpolation = .high
draw(in: NSRect(origin: .zero, size: NSSize(width: newWidth,height: newHeight)), from: NSRect(origin: .zero, size: size) , operation: .copy, fraction: 1)
img.unlockFocus()
return img
}
}
请查看调整大小后的示例图像。我已标记图像。调整大小的代码在其他情况下似乎运行良好。请给予建议。
更新: @LeoDabus 我使用了你的代码,对于输出尺寸为1084X2086像素,它产生了类似的结果。我不得不稍微修改你的代码 - 只有一行因为它无法编译。编译器自动建议了它。 NSGraphicsContext.current()?.imageInterpolation = .high
func resizeTo(width: CGFloat, height: CGFloat) -> NSImage {
let ratioX = width / size.width
let ratioY = height / size.height
let ratio = ratioX < ratioY ? ratioX : ratioY
let newHeight = size.height * ratio
let newWidth = size.width * ratio
let canvasSize = CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))
let img = NSImage(size: canvasSize)
img.lockFocus()
NSGraphicsContext.current()?.imageInterpolation = .high
draw(in: NSRect(origin: CGPoint(x: (canvasSize.width - (size.width * ratio)) / 2, y: (canvasSize.height - (size.height * ratio)) / 2), size: NSSize(width: newWidth,height: newHeight)), from: NSRect(origin: .zero, size: size), operation: .copy, fraction: 1)
img.unlockFocus()
return img
}