ios - 如何将多个 mask 应用于 UIView

标签 ios swift uiview mask cashapelayer

我有一个问题,关于如何将多个 mask 应用到已经有 mask 的 UIView。

情况:
我有一个带有事件 mask 的 View ,在其左上角创建了一个洞,这是一个模板 UIView,可在项目的任何地方重复使用。在项目的后期,我希望能够创建第二个孔,但这次是在右下角,这不需要创建一个全新的 UIView。

问题:
当我应用底部面膜时,它当然会取代第一个面膜,从而去除顶部孔......有没有办法将它们结合起来?就此而言,将任何现有面具与新面具结合起来?

提前致谢!

最佳答案

根据@Sharad 的回答,我意识到重新添加 View 的矩形将使我能够将原始蒙版和新蒙版合二为一。

这是我的解决方案:

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
}

关于ios - 如何将多个 mask 应用于 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50719484/

相关文章:

ios - MPMusicPlayerController.systemMusicPlayer 和 AirPlay 的播放信息?

ios - UITableView 单元格行为不当,显示没有披露等

swift - Realm 中没有 addNotificationBlock 方法。它在哪里?

swift - 图像的 Collectionview 布局

swift - 如何实现 Enum 对案例进行论证

iphone - 这是什么类型的事件动画 View ?

ios - 动画约束时高度 anchor 的自动布局错误

ios - 我如何可以动画化 UINavigationBar 而不是 UITabBar 的条形色调颜色的变化?

iphone - UIScrollView 作为 subview 不滚动

ios - 如何根据单元格内容更改单元格高度?