Swift 如何在一张图片上打一个圆形的透明空洞
2021-09-13 本文已影响0人
sampson666888
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let imageView = UIImageView()
self.view.addSubview(imageView)
imageView.frame = self.view.bounds
imageView.image = getImage()
}
func getImage() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, false, 0.0)
let ctx = UIGraphicsGetCurrentContext()
let area = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height)
ctx?.scaleBy(x: 1, y: -1)
ctx?.translateBy(x: 0, y: -area.size.height)
ctx?.setBlendMode(.multiply)
let maskPath: UIBezierPath = UIBezierPath(rect: area)
let holePath: UIBezierPath = UIBezierPath(roundedRect: CGRect(x: 100, y: 100, width: 50, height: 50), cornerRadius: 25)
ctx?.addPath(maskPath.cgPath)
ctx?.addPath(holePath.cgPath)
ctx?.clip(using: .evenOdd)
ctx?.clip()
ctx?.draw(UIImage(named: "1.png")!.cgImage!, in: area)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}