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