美文网首页
Swift 如何在一张图片上打一个圆形的透明空洞

Swift 如何在一张图片上打一个圆形的透明空洞

作者: sampson666888 | 来源:发表于2021-09-13 15:19 被阅读0次
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
}

相关文章

网友评论

      本文标题:Swift 如何在一张图片上打一个圆形的透明空洞

      本文链接:https://www.haomeiwen.com/subject/mdpcgltx.html