circle image in cell imageView and how to resize it?

后端 未结 3 898
孤街浪徒
孤街浪徒 2021-01-29 00:21

I have in a ViewController tableView with the identifier \"Cell\". This is my code:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSInd         


        
3条回答
  •  无人及你
    2021-01-29 00:54

    You can use this extension to crop the longest side of your image and return a squared UIImage:

    extension UIImage {
        var squared: UIImage {
            let square = size.width < size.height ? CGSize(width: size.width, height: size.width) : CGSize(width: size.height, height: size.height)
            let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: square))
            imageView.contentMode = UIViewContentMode.ScaleAspectFill
            imageView.image = self
            UIGraphicsBeginImageContext(imageView.bounds.size)
            imageView.layer.renderInContext(UIGraphicsGetCurrentContext())
            let result = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return result
        }
        var circle: UIImage {
            let square = size.width < size.height ? CGSize(width: size.width, height: size.width) : CGSize(width: size.height, height: size.height)
            let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: square))
            imageView.contentMode = UIViewContentMode.ScaleAspectFill
            imageView.image = self
            imageView.layer.cornerRadius = square.width/2
            imageView.layer.masksToBounds = true
            UIGraphicsBeginImageContext(imageView.bounds.size)
            imageView.layer.renderInContext(UIGraphicsGetCurrentContext())
            let result = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return result
        }
        func resizeToWidth(width:Int)-> UIImage {
            let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: CGFloat(width), height: CGFloat(ceil(CGFloat(width)/size.width * size.height)))))
            imageView.contentMode = UIViewContentMode.ScaleAspectFit
            imageView.image = self
            UIGraphicsBeginImageContext(imageView.bounds.size)
            imageView.layer.renderInContext(UIGraphicsGetCurrentContext())
            let result = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return result
        }
    
    }
    

提交回复
热议问题