2017-10-06 2 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 (height * ratioX, 크기 width의)를 사용하여 캔버스를 만들 수 있습니다. newWidthnewHeight을 사용하여 캔버스를 만들어야한다고 말하고 싶습니다.

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

또한이 스크립트는 양방향으로 크기가 조정되므로 작은 이미지의 크기가 커질 수 있습니다.

+0

알았어. 어떻게 코드를 개선 할 수 있습니까? – techno

+0

이미지의 크기를 늘리지 않기 위해 코드를 향상시키려는 경우 ratio :'if (ratio)> 0 ratio = 1;' – Gedrox

+0

의 체크를 덧붙이면'var ratio = ratioX 0 { 비율 = 1 } – techno