Siddharthan Asokan
Siddharthan Asokan

Reputation: 4441

Creating a transparent hole on UIVisualEffect view

I'm trying to create a transparent hole kind of view on the UIVisualEffectView. I was following the solution given here. I have attached my sample code which I worked on here. I'm trying to create a transparent view whose frame is taken from the image view behind the blurry view. Anyone could tell me what is that I'm doing wrong here?

Upvotes: 12

Views: 2307

Answers (2)

ergunkocak
ergunkocak

Reputation: 3380

Swift 5 version of the solution for lazy ones :)

    var roundedRect = visualEffectsView.bounds
    roundedRect.origin.x = roundedRect.size.width / 4
    roundedRect.origin.y = roundedRect.size.height / 4
    roundedRect.size.width = roundedRect.size.width / 2
    roundedRect.size.height = roundedRect.size.height / 2

    let cornerRadius = roundedRect.size.height / 2

    let path = UIBezierPath(rect: visualEffectsView.bounds)
    let croppedPath = UIBezierPath(roundedRect: roundedRect, cornerRadius: cornerRadius)
    path.append(croppedPath)
    path.usesEvenOddFillRule = true

    let mask = CAShapeLayer()
    mask.path = path.cgPath
    mask.fillRule = .evenOdd
    visualEffectsView.layer.mask = mask

Upvotes: 2

cnotethegr8
cnotethegr8

Reputation: 7510

You can use a UIBezierPath to create the mask you want.

blurView.layer.mask = ({
    CGRect roundedRect = self.bounds;
    roundedRect.origin.x = roundedRect.size.width / 4.0f;
    roundedRect.origin.y = roundedRect.size.height / 4.0f;
    roundedRect.size.width /= 2.0f;
    roundedRect.size.height /= 2.0f;

    CGFloat cornerRadius = roundedRect.size.height / 2.0f;

    UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.bounds];
    UIBezierPath *croppedPath = [UIBezierPath bezierPathWithRoundedRect:roundedRect cornerRadius:cornerRadius];
    [path appendPath:croppedPath];
    [path setUsesEvenOddFillRule:YES];

    CAShapeLayer *mask = [CAShapeLayer layer];
    mask.path = path.CGPath;
    mask.fillRule = kCAFillRuleEvenOdd;
    mask;
});

Upvotes: 14

Related Questions