Using cornerRadius on a UIImageView in a UITableViewCell

前端 未结 4 1090
情歌与酒
情歌与酒 2021-01-31 11:55

I\'m using a UIImageView for each of my UITableViewCells, as thumbnails. My code uses SDWebImage to asynchronously grab those images from

4条回答
  •  不思量自难忘°
    2021-01-31 12:19

    Swift 3 version of thedeveloper3124's answer

    func roundedImage(image: UIImage, completion: @escaping ((UIImage?)->(Void))) {
        DispatchQueue.global().async {
            // Begin a new image that will be the new image with the rounded corners
            // (here with the size of an UIImageView)
            UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
            let rect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
    
            // Add a clip before drawing anything, in the shape of an rounded rect
            UIBezierPath(roundedRect: rect, cornerRadius: image.size.width/2).addClip()
    
            // Draw your image
            image.draw(in: rect)
    
            // Get the image, here setting the UIImageView image
            guard let roundedImage = UIGraphicsGetImageFromCurrentImageContext() else {
                print("UIGraphicsGetImageFromCurrentImageContext failed")
                completion(nil)
                return
            }
    
            // Lets forget about that we were drawing
            UIGraphicsEndImageContext()
    
            DispatchQueue.main.async {
                completion(roundedImage)
            }
        }
    }
    

提交回复
热议问题