2017-10-11 6 views
2

次の一般的なコードを使用して画像のサイズを変更しようとしていますが、画像のサイズを変更していますが、画像サイズをScale to Fillと変更した場合、サイズを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

にその内容モードを設定します局面においてNewSizeパラメータを設定しようとしたしました元の画像サイズの比率。必要に応じて幅が幅ごとに高さを計算し直すと、あなたは、高さの修正をしたいならば、高さ幅が修正され

計算高さごとに幅を計算:高さが修正されたとき

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、ここ

関連する問題