CAShapeLayer mask view

2019-03-01 23:12发布

I have one problem. I look for the answers on the net and I don't understand why is not working. I must do some stupid mistake which I can't figure it out.

if I make :

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(10, 10, 300, 400)];
    view.backgroundColor = [UIColor blueColor];
    [self.view addSubview:view];

}

it create blue view on the screen, but if I make

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(10, 10, 300, 400)];
    view.backgroundColor = [UIColor blueColor];
    [self.view addSubview:view];

    CAShapeLayer * layer = [[CAShapeLayer alloc]init];
    layer.frame = CGRectMake(10, 10, 30, 30);
    layer.fillColor = [[UIColor blackColor] CGColor];

    view.layer.mask = layer;

}

it don't show anything.

If I understand correctly it should mask at (10,10,30,30)?

2条回答
不美不萌又怎样
2楼-- · 2019-03-01 23:39

Thanks for the answer, cncool.

In case someone can't find suitable answer on SO for this question for hours, like i just did, i've assembled a working gist in Swift 2.2 for masking/clipping UIView with CGRect/UIBezierPath:

https://gist.github.com/Flar49/7e977e81f1d2827f5fcd5c6c6a3c3d94

extension UIView {
    func mask(withRect rect: CGRect, inverse: Bool = false) {
        let path = UIBezierPath(rect: rect)
        let maskLayer = CAShapeLayer()

        if inverse {
            path.appendPath(UIBezierPath(rect: self.bounds))
            maskLayer.fillRule = kCAFillRuleEvenOdd
        }

        maskLayer.path = path.CGPath

        self.layer.mask = maskLayer
    }

    func mask(withPath path: UIBezierPath, inverse: Bool = false) {
        let path = path
        let maskLayer = CAShapeLayer()

        if inverse {
            path.appendPath(UIBezierPath(rect: self.bounds))
            maskLayer.fillRule = kCAFillRuleEvenOdd
        }

        maskLayer.path = path.CGPath

        self.layer.mask = maskLayer
    }
}

Usage:

let viewSize = targetView.bounds.size
let rect = CGRect(x: 20, y: 20, width: viewSize.width - 20*2, height: viewSize.height - 20*2)

// Cuts rectangle inside view, leaving 20pt borders around
targetView.mask(withRect: rect, inverse: true)

// Cuts 20pt borders around the view, keeping part inside rect intact
targetView.mask(withRect: rect)

Hope it will save someone some time in the future :)

查看更多
女痞
3楼-- · 2019-03-01 23:51

You need to set the path on the CAShapeLayer:

- (void)viewDidLoad
{
    [super viewDidLoad];


    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(10, 10, 300, 400)];
    view.backgroundColor = [UIColor blueColor];
    [self.view addSubview:view];

    CAShapeLayer * layer = [[CAShapeLayer alloc]init];
    layer.frame = view.bounds;
    layer.fillColor = [[UIColor blackColor] CGColor];

    layer.path = CGPathCreateWithRect(CGRectMake(10, 10, 30, 30), NULL);

    view.layer.mask = layer;
}
查看更多
登录 后发表回答