您可以使用此命令对UIImage进行四舍五入:
func roundedImage(from image: UIImage, radius: CGFloat) -> UIImage {
let frame = CGRect(x: 0, y: 0, width: 2 * radius, height: 2 * radius)
let imageView: UIImageView = UIImageView(frame: frame)
imageView.image = image
let layer = imageView.layer
layer.masksToBounds = true
layer.cornerRadius = radius
UIGraphicsBeginImageContext(imageView.bounds.size)
layer.render(in: UIGraphicsGetCurrentContext()!)
let roundedImg = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return roundedImg!
}
let img = UIImage(named: "NameOfTheImage")!
let r: CGFloat = 300
roundedImage(from: img, withRadius: r)
UIGraphicsBeginImageContext(newImageView.bounds.size)
let frame = CGRect(x: 30, y: screenHeight/2 - radius/2 + 30, width: radius - 60, height: radius - 60)
guard let img = imageView.image, let cgImage = img.cgImage, let croppedCGImage = cgImage.cropping(to: frame) else {
fatalError("Couldn't crop the image")
}
let newImage = UIImage(cgImage: croppedCGImage)
let newImageView: UIImageView = UIImageView(image: newImage)
let layer = newImageView.layer
layer.masksToBounds = true
layer.cornerRadius = radius
layer.render(in: UIGraphicsGetCurrentContext()!)
guard let roundedImg = UIGraphicsGetImageFromCurrentImageContext() else {
fatalError("Couldn't render the image")
}
UIGraphicsEndImageContext()
// use roundedImg