0
我试图通过保持纵横比来调整图像大小。但是在调整大小的图像周围存在此空白区域。调整图像周围的白色空间
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
}
}
我我做错了什么?
好的..我该如何改进代码。请咨询。 – techno
如果你的意思是改善代码不增加图像的大小,只需添加检查比例:'if(ratio)> 0 ratio = 1;' – Gedrox
所以我这样做'var ratio = ratioX 0 { ratio = 1 } ' –
techno