UIView中的CAShapeLayer抠图 [英] CAShapeLayer cutout in UIView

查看:65
本文介绍了UIView中的CAShapeLayer抠图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是创建带有透明圆角矩形插图的漂亮的不透明背景

My goal is to create a pretty opaque background with a clear rounded rect inset

    let shape = CGRect(x: 0, y: 0, width: 200, height: 200)

    let maskLayer = CAShapeLayer()
    maskLayer.path = UIBezierPath(roundedRect: shape, cornerRadius: 16).cgPath
    maskLayer.fillColor = UIColor.clear.cgColor
    maskLayer.fillRule = kCAFillRuleEvenOdd

    let background = UIView()
    background.backgroundColor = UIColor.black.withAlphaComponent(0.8)
    view.addSubview(background)
    constrain(background) {
        $0.edges == $0.superview!.edges
    }

    background.layer.addSublayer(maskLayer)
//        background.layer.mask = maskLayer

当我取消注释 background.layer.mask = maskLayer 时,视图完全清晰.注释掉后,我看到半透明的背景颜色,但没有蒙版切口

When I uncomment background.layer.mask = maskLayer, the view is totally clear. When I have it commented out, I see the semi-opaque background color but no mask cutout

知道我在做什么错吗?谢谢!

Any idea what I'm doing wrong here? Thanks!

推荐答案

这里是一个操场,我认为它可以实现您的预​​期效果(减去 .edges constrain -似乎是您自己的扩展程序).

Here is a playground that I think implements your intended effect (minus .edges and constrain - that appear to be your own extensions).

a)使用红色背景代替带有alpha的黑色背景(只是为了使效果突出)

a) used a red background instead of black with alpha (just to make the effect stand out)

b)设置 maskLayer.backgroundColor 而不是 maskLayer.fillColor

将maskLayer作为另一层添加到 uiview 中是多余的(如@Ken所示),但似乎没有害处.

Adding the maskLayer as another layer to uiview is superfluous (as indicated by @Ken) but seems to do no harm.

    import UIKit
    import PlaygroundSupport


    let bounds = CGRect(x: 0, y: 0, width: 400, height: 200)

    let uiview = UIView(frame: bounds)
    uiview.backgroundColor = UIColor.red.withAlphaComponent(0.8)

    PlaygroundPage.current.liveView = uiview

    let shape = CGRect(x: 100, y: 50, width: 200, height: 100)


    let maskLayer = CAShapeLayer()
    maskLayer.path = UIBezierPath(roundedRect: shape, cornerRadius: 16).cgPath
    maskLayer.backgroundColor = UIColor.clear.cgColor
    maskLayer.fillRule = kCAFillRuleEvenOdd
    uiview.layer.mask = maskLayer

清晰插图的图像

另一方面,如果您打算使用如下所示的相框/彩色信封-透明窗口效果,请参阅要点

On the other hand, if you intended a picture frame / colored-envelope-with-transparent-window effect like below, then see gist

相框图像

这篇关于UIView中的CAShapeLayer抠图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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