swift - 头像图片裁切

let image = UIImage(named: "chang.jpg")
let imageview = UIImageView(image: image?.thumbnailWithImageWithoutScale(asize: CGSize(width: 100, height: 100)))
imageview.frame = CGRect(x: 50, y: 200, width: 100, height: 100)
imageview.layer.borderWidth = 5
imageview.layer.masksToBounds = true
imageview.layer.cornerRadius = 100 / 2
self.view.addSubview(imageview)

extension UIImage {
    func thumbnailWithImageWithoutScale(asize: CGSize) -> UIImage {
        
        let newimage: UIImage
        
        let oldsize = self.size
        var rect: CGRect = CGRect()
        if asize.width/asize.height > oldsize.width/oldsize.height {
            rect.size.width = asize.height*oldsize.width/oldsize.height * 1.5;
            rect.size.height = asize.height * 1.5;
            rect.origin.x = (asize.width - rect.size.width)/2;
            rect.origin.y = 0
        } else {
            rect.size.width = asize.width;
            rect.size.height = asize.width*oldsize.height/oldsize.width;
            rect.origin.x = 0;
            rect.origin.y = (asize.height - rect.size.height)/2;
        }

        UIGraphicsBeginImageContext(asize);
        let context = UIGraphicsGetCurrentContext();
        context!.setFillColor(UIColor.clear.cgColor);
        UIRectFill(CGRect(x: 0, y: 0, width: asize.width, height: asize.height));//clear background
        self.draw(in: rect)
        
        newimage = UIGraphicsGetImageFromCurrentImageContext()!;
        UIGraphicsEndImageContext();
        return newimage;
    }
}

你可能感兴趣的:(swift - 头像图片裁切)