はじめに
アルバムなどに入っている長方形の画像(UIImage)から、中心部分を正方形にトリミングしてUIImageViewで円形に表示させる方法を紹介します。
画像を指定した幅にリサイズ -> 中心部分を正方形に切り抜く -> cornerRadiusで円形表示
コード
まず、UIImageのextensionでリサイズと切り抜きを行います。
引数のresizeWidthで画面に表示するときの幅を指定します。
extension UIImage {
// リサイズして正方形にトリミング
func cropResizedSquare(_ resizeWidth: CGFloat) -> UIImage? {
let minSideWidth = min(size.width, size.height)
let ratio = resizeWidth / minSideWidth
let origin = size.width > size.height
? CGPoint(x: (minSideWidth - size.width) * 0.5 * ratio, y: 0.0)
: CGPoint(x: 0.0, y: (minSideWidth - size.height) * 0.5 * ratio)
// リサイズ
UIGraphicsBeginImageContextWithOptions(CGSize(width: resizeWidth, height: resizeWidth), false, 0.0)
// トリミング
draw(in: CGRect(origin: origin, size: CGSize(width: size.width * ratio, height: size.height * ratio)))
let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resizedImage
}
}
最後に、UIImageからこのメソッドを呼び出し、UIImageViewのcornerRadiusで画像を円形に表示させます。
let myImage = UIImage(named: "myImage") // 表示させたい画像
let imageWidth: CGFloat = 50 // 表示するときの幅
let imageView = UIImageView()
imageView.image = myImage?.cropResizedSquare(imageWidth)
imageView.layer.cornerRadius = imageWidth * 0.5
imageView.clipsToBounds = true