2017-10-06 125 views
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 
    } 
} 

enter image description here

我我做錯了什麼?

回答

1

首先要從ratioXratioY採摘最小的比例,但後來創建使用ratioX(,大小widthheight * ratioX)的畫布。我想說你需要使用newWidthnewHeight創建畫布。

let canvasSize = CGSize(width: newWidth, height: newHeight) 

此外,請注意,此腳本將在兩個方向上調整大小,即將增加小圖像的大小。

+0

好的..我該如何改進代碼。請諮詢。 – techno

+0

如果你的意思是改善代碼不增加圖像的大小,只需添加檢查比例:'if(ratio)> 0 ratio = 1;' – Gedrox

+0

所以我這樣做'var ratio = ratioX 0 { ratio = 1 } ' – techno