CALayer with transparent hole in it

后端 未结 5 601
误落风尘
误落风尘 2020-11-28 17:28

I have a simple view (left side of the picture) and i need to create some kind of overlay (right side of the picture) to this view. This overlay should have some opacity, so

5条回答
  •  独厮守ぢ
    2020-11-28 18:12

    I was able to solve this with Jon Steinmetz suggestion. If any one cares, here's the final solution:

    int radius = myRect.size.width;
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, self.mapView.bounds.size.width, self.mapView.bounds.size.height) cornerRadius:0];
    UIBezierPath *circlePath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0*radius, 2.0*radius) cornerRadius:radius];
    [path appendPath:circlePath];
    [path setUsesEvenOddFillRule:YES];
    
    CAShapeLayer *fillLayer = [CAShapeLayer layer];
    fillLayer.path = path.CGPath;
    fillLayer.fillRule = kCAFillRuleEvenOdd;
    fillLayer.fillColor = [UIColor grayColor].CGColor;
    fillLayer.opacity = 0.5;
    [view.layer addSublayer:fillLayer];
    

    Swift 3.x:

    let radius = myRect.size.width
    let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.mapView.bounds.size.width, height: self.mapView.bounds.size.height), cornerRadius: 0)
    let circlePath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 2 * radius, height: 2 * radius), cornerRadius: radius)
    path.append(circlePath)
    path.usesEvenOddFillRule = true
    
    let fillLayer = CAShapeLayer()
    fillLayer.path = path.cgPath
    fillLayer.fillRule = kCAFillRuleEvenOdd
    fillLayer.fillColor = Color.background.cgColor
    fillLayer.opacity = 0.5
    view.layer.addSublayer(fillLayer)
    

    Swift 4.2 & 5:

    let radius: CGFloat = myRect.size.width
    let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height), cornerRadius: 0)
    let circlePath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 2 * radius, height: 2 * radius), cornerRadius: radius)
    path.append(circlePath)
    path.usesEvenOddFillRule = true
    
    let fillLayer = CAShapeLayer()
    fillLayer.path = path.cgPath
    fillLayer.fillRule = .evenOdd
    fillLayer.fillColor = view.backgroundColor?.cgColor
    fillLayer.opacity = 0.5
    view.layer.addSublayer(fillLayer)
    

提交回复
热议问题