- (void)showViewRect:(CGRect)rect cornerRadius:(CGFloat)cornerRadius
{
[[UIApplication sharedApplication].keyWindow addSubview:self];
CGRect frame = [UIScreen mainScreen].bounds;
[self addSubview:self.imageView];
// 第一個(gè)路徑
UIBezierPath *path = [UIBezierPath bezierPathWithRect:frame];
// 透明path
UIBezierPath *path2 = [[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:cornerRadius] bezierPathByReversingPath];
[path appendPath:path2];
// 繪制透明區(qū)域
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = path.CGPath;
[self.layer setMask:shapeLayer];
self.imageView.centerX = CGRectGetCenter(rect).x - self.imageView.width * 0.5;
self.imageView.y = CGRectGetMaxY(rect) + 20;
}
@implementation UIView (Guide)
- (void)hollowWithRect:(CGRect)rect cornerRadius:(CGFloat)cornerRadius
{
CGRect frame = self.bounds;
// 第一個(gè)路徑
UIBezierPath *path = [UIBezierPath bezierPathWithRect:frame];
// 透明path
UIBezierPath *path2 = [[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:cornerRadius] bezierPathByReversingPath];
[path appendPath:path2];
// 繪制透明區(qū)域
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = path.CGPath;
[self.layer setMask:shapeLayer];
}
- (void)outLineWithlineWidth:(CGFloat)lineWidth
strokeColor:(UIColor *)strokeColor
fillColor:(UIColor *)fillColor
cornerRadius:(CGFloat)cornerRadius
{
CAShapeLayer *border = [CAShapeLayer layer];
//虛線的顏色
border.strokeColor = strokeColor.CGColor;
//填充的顏色
border.fillColor = fillColor.CGColor;
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:cornerRadius];
//設(shè)置路徑
border.path = path.CGPath;
border.frame = self.bounds;
//虛線的寬度
border.lineWidth = lineWidth;
//設(shè)置線條的樣式
// border.lineCap = @"square";
//虛線的間隔
border.lineDashPattern = @[@4, @2];
self.layer.cornerRadius = cornerRadius;
self.layer.masksToBounds = YES;
[self.layer addSublayer:border];
}
@end
如果是要挖多個(gè)區(qū)域,上面的設(shè)置layer.mask方法就不行别威,需要用下下面的方法:
- (void)hollowWithRect:(CGRect)rect1
rect2:(CGRect)rect2
cornerRadius:(CGFloat)cornerRadius {
[self.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)];
CGRect frame = self.bounds;
//整體區(qū)域
UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRect:frame];
//指定區(qū)域
UIBezierPath *clearPath = [UIBezierPath bezierPathWithRoundedRect:rect1 cornerRadius:cornerRadius];
[bezierPath appendPath: clearPath];
if (!CGRectEqualToRect(rect2, CGRectZero)) {
UIBezierPath *clearPath2 = [UIBezierPath bezierPathWithRoundedRect:rect2 cornerRadius:cornerRadius];
[bezierPath appendPath: clearPath2];
}
[bezierPath setUsesEvenOddFillRule:YES];
//創(chuàng)建layer顯示
CAShapeLayer *Layer1 = [CAShapeLayer layer];
Layer1.path = bezierPath.CGPath;
[Layer1 setFillRule:kCAFillRuleEvenOdd];
Layer1.opacity = 0.85;
//添加到View上
[self.layer addSublayer:Layer1];
}