0

这是我正在使用的代码

extension UIImage {        
    var ellipseMasked: UIImage? {
        guard let cgImage = cgImage else { return nil }
        let rect = CGRect(origin: .zero, size: size)

        return UIGraphicsImageRenderer(size: size, format: imageRendererFormat)
            .image{ _ in
                UIBezierPath(ovalIn: rect).addClip()
                UIImage(cgImage: cgImage, scale: scale, orientation: imageOrientation)
            .draw(in: rect)
        }
    }
}

这是我得到的图像

背景颜色为黑色。我怎样才能使背景透明?我尝试了不同的方法,但还没有成功。

4

1 回答 1

2

您可以继承 UIImageView 并屏蔽其 CALayer 而不是剪切图像本身:

extension CAShapeLayer {
    convenience init(path: UIBezierPath) {
        self.init()
        self.path = path.cgPath
    }
}

class EllipsedView: UIImageView {
    override func layoutSubviews() {
        super.layoutSubviews()
        layer.mask = CAShapeLayer(path: .init(ovalIn: bounds))
    }
}

let profilePicture = UIImage(data: try! Data(contentsOf: URL(string:"http://i.stack.imgur.com/Xs4RX.jpg")!))!
let iv = EllipsedView(image: profilePicture)

编辑/更新

如果你需要剪辑UIImage自己,你可以这样做:

extension UIImage {
    var ellipseMasked: UIImage? {
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        defer { UIGraphicsEndImageContext() }
        UIBezierPath(ovalIn: .init(origin: .zero, size: size)).addClip()
        draw(in: .init(origin: .zero, size: size))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

对于 iOS10+,您可以使用UIGraphicsImageRenderer.

extension UIImage {
    var ellipseMasked: UIImage {
        let rect = CGRect(origin: .zero, size: size)
        let format = imageRendererFormat
        format.opaque = false
        return UIGraphicsImageRenderer(size: size, format: format).image{ _ in
            UIBezierPath(ovalIn: rect).addClip()
            draw(in: rect)
        }
    }
}

let profilePicture = UIImage(data: try! Data(contentsOf: URL(string:"http://i.stack.imgur.com/Xs4RX.jpg")!))!
profilePicture.ellipseMasked

在此处输入图像描述

于 2020-01-18T22:06:02.537 回答