我正在尝试通过保持纵横比来调整图像大小。但是调整后的图像周围有这个空白区域。
extension NSImage {
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()
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
}
}
我做错了什么?
最佳答案
首先,您从 ratioX
和 ratioY
中选择最小的比率,但稍后您使用 ratioX
(大小为 width
, height * ratioX
).我会说您需要使用 newWidth
和 newHeight
创建 Canvas 。
let canvasSize = CGSize(width: newWidth, height: newHeight)
此外,请注意此脚本会在两个方向调整大小,即会增加小图像的大小。
关于swift - 调整大小的图像周围的空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46604193/