如何将多个蒙版应用于UIView [英] How to apply multiple masks to UIView

查看:124
本文介绍了如何将多个蒙版应用于UIView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,关于如何将多个蒙版应用于已经具有蒙版的UIView.

I have a question about how to apply multiple masks to a UIView that already has a mask.

情况:
我有一个带有活动蒙版的视图,该蒙版在其左上角创建了一个孔,这是一个模板UIView,可在项目中的任何地方重复使用.在项目的后面,我希望能够创建第二个孔,但这一次是在右下角,而无需创建全新的UIView.

The situation:
I have a view with an active mask that creates a hole in its top left corner, this is a template UIView that is reused everywhere in the project. Later in the project I would like to be able to create a second hole but this time in the bottom right corner, this without the need to create a completely new UIView.

问题:
当我使用底面膜时,它当然会替换第一个底面膜,从而去除顶孔.有没有办法将两者结合起来?那么,要将现有的遮罩与新的遮罩结合起来吗?

The problem:
When I apply the bottom mask, it of course replaces the first one thus removing the top hole ... Is there a way to combine them both? And for that matter to combine any existing mask with a new one?

提前谢谢!

推荐答案

基于@Sharad的回答,我意识到重新添加视图的rect将使我能够将原始蒙版和新蒙版组合为一个蒙版.

Based on @Sharad's answer, I realised that re-adding the view's rect would enable me to combine the original and new mask into one.

这是我的解决方案:

func cutCircle(inView view: UIView, withRect rect: CGRect) {

    // Create new path and mask
    let newMask = CAShapeLayer()
    let newPath = UIBezierPath(ovalIn: rect)

    // Create path to clip
    let newClipPath = UIBezierPath(rect: view.bounds)
    newClipPath.append(newPath)

    // If view already has a mask
    if let originalMask = view.layer.mask,
        let originalShape = originalMask as? CAShapeLayer,
        let originalPath = originalShape.path {

        // Create bezierpath from original mask's path
        let originalBezierPath = UIBezierPath(cgPath: originalPath)

        // Append view's bounds to "reset" the mask path before we re-apply the original
        newClipPath.append(UIBezierPath(rect: view.bounds))

        // Combine new and original paths
        newClipPath.append(originalBezierPath)

    }

    // Apply new mask
    newMask.path = newClipPath.cgPath
    newMask.fillRule = kCAFillRuleEvenOdd
    view.layer.mask = newMask
}

这篇关于如何将多个蒙版应用于UIView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆