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
這是我一直用它來調整我的圖片https://gist.github.com/tomasbasham/10533743#gistcomment-1988471一個良好的擴展 – Callam
我試着那麼,他們確實縮小了比例以適應方面,但圖像模糊 – Coder221
您可以分享代碼,瞭解如何在視圖中設置圖像嗎?另外,你如何設置上述視圖的contentMode? – NSAdi