2017-10-11 46 views
2

我正在嘗試使用以下熱門代碼調整圖像大小並調整圖像大小,但它將圖像大小調整爲Scale to Fill,我想將它們調整爲Aspect Fit.我該怎麼做?將圖像調整爲Aspect Fit

func resizeImage(image: UIImage, newSize: CGSize) -> (UIImage) { 

    let newRect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height).integral 
    UIGraphicsBeginImageContextWithOptions(newSize, true, 0) 
    let context = UIGraphicsGetCurrentContext() 

    // Set the quality level to use when rescaling 
    context!.interpolationQuality = CGInterpolationQuality.default 
    let flipVertical = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: newSize.height) 
    context!.concatenate(flipVertical) 

    // Draw into the context; this scales the image 
    context?.draw(image.cgImage!, in: CGRect(x: 0.0,y: 0.0, width: newRect.width, height: newRect.height)) 

    let newImageRef = context!.makeImage()! as CGImage 
    let newImage = UIImage(cgImage: newImageRef) 

    // Get the resized image from the context and a UIImage 
    UIGraphicsEndImageContext() 

    return newImage 
} 

我已經設置圖像的內容模式Aspect Fit但它仍然是行不通的。

這是我在我的收藏視圖控制器稱爲上面的代碼

cell.imageView.image = UIImage(named: dogImages[indexPath.row])?.resizeImage(image: UIImage(named: dogImages[indexPath.row]) 

我手動選擇我的形象在故事板,並設置其內容模式apsect fit

+0

這是我一直用它來調整我的圖片https://gist.github.com/tomasbasham/10533743#gistcomment-1988471一個良好的擴展 – Callam

+0

我試着那麼,他們確實縮小了比例以適應方面,但圖像模糊 – Coder221

+0

您可以分享代碼,瞭解如何在視圖中設置圖像嗎?另外,你如何設置上述視圖的contentMode? – NSAdi

回答

0

你嘗試設置新尺寸的方面原始圖像大小的比例。如果你想寬度修正計算高度按寬度,如果你想要的高度固定,然後計算出寬度爲每高度的時候寬度是固定

計算高度:

let fixedWidth: CGFloat = 200 
    let newHeight = fixedWidth * image.size.height/image.size.width 
    let convertedImage = resizeImage(image: image, newSize: CGSize(width: fixedWidth, height: newHeight)) 

計算寬度時,高度修正:

let fixedheight: CGFloat = 200 
    let newWidth = fixedheight * image.size.width/image.size.height 
    let convertedImage = resizeImage(image: image, newSize: CGSize(width: newWidth, height: fixedheight)) 

您可以使用此調整大小的圖像與縱橫比擬合。

還檢查了答案:https://stackoverflow.com/a/8858464/2677551,可以幫助