重写View的drawRect方法
- (instancetype)initWithTargetView:(UIView *)targetView
{
self = [super init];
if (self) {
self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
self.frame = [UIScreen mainScreen].bounds;
self.alpha = 0;
_targetView = targetView;
}
return self;
}
+ (instancetype)guideViewWithTargetView:(UIView *)targetView{
return [[GuideView alloc] initWithTargetView:targetView];
}
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
if (self.targetView) {
CGRect frame = [self.targetView convertRect:self.targetView.bounds toView:kAppDelegate.window];
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextClearRect(ctx, frame);
}
}
- (void)show{
[kAppDelegate.window addSubview:self];
[UIView animateWithDuration:0.3 animations:^{
self.alpha = 1;
}];
}
- (void)disMiss{
[UIView animateWithDuration:0.3 animations:^{
self.alpha = 0;
} completion:^(BOOL finished) {
[self removeFromSuperview];
}];
}
- (void)addTarget:(id)target action:(SEL)action{
[self disMiss];
}
如果想要裁剪出一个圆的话,则需要结合贝塞尔曲线了
CGRect frame = [view convertRect:view.bounds toView:kAppDelegate.window];// 把你想要露出来的view传进来就行
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:kAppDelegate.window.bounds cornerRadius:0];
UIBezierPath *circlePath = [UIBezierPath bezierPathWithRoundedRect:frame cornerRadius:view.width/2.0];
[path appendPath:circlePath];
[path setUsesEvenOddFillRule:YES];
CAShapeLayer *fillLayer = [CAShapeLayer layer];
fillLayer.path = path.CGPath;
fillLayer.fillRule = kCAFillRuleEvenOdd;
fillLayer.fillColor = [UIColor blackColor].CGColor;
fillLayer.opacity = 0.3;
[self.layer addSublayer:fillLayer];
也可以通过layer的Mask实现
CGRect frame = [view convertRect:view.bounds toView:kAppDelegate.window]; // 把你想要露出来的view传进来
UIBezierPath *path = [UIBezierPath bezierPathWithRect:kAppDelegate.window.bounds];
[path appendPath:[[UIBezierPath bezierPathWithRoundedRect:frame cornerRadius:view.layer.cornerRadius] bezierPathByReversingPath]];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = path.CGPath;
[self.layer setMask:shapeLayer];