- 有时候功能引导页需要对指定部分可见,其余为黑色遮罩.这时候需要用到图层绘制
方法一:用CAShapeLayer
- 实现一个镂空加描边的蒙版
#import "GuideView.h"
#define MLScreenH [UIScreen mainScreen].bounds.size.height
#define MLScreenW [UIScreen mainScreen].bounds.size.width
@implementation GuideView
- (instancetype)init{
self = [super init];
self.frame = CGRectMake(0, 0, MLScreenW, MLScreenH);
[self drawBorderMaskLayer];
return self;
}
- (void)drawBorderMaskLayer{
//描边
CGRect alphaRect = CGRectMake(10, 100, 100, 100);
CGFloat cornerRadius = 10;
CAShapeLayer *borderLayer = [CAShapeLayer layer];
borderLayer.frame = self.bounds;
borderLayer.lineWidth = 3;
borderLayer.strokeColor = [UIColor redColor].CGColor;
borderLayer.fillColor = [UIColor clearColor].CGColor;
UIBezierPath *bezierPath=[UIBezierPath bezierPathWithRoundedRect:alphaRect
cornerRadius:cornerRadius];
borderLayer.path = bezierPath.CGPath;
[self.layer insertSublayer:borderLayer atIndex:0];
{//镂空
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = self.bounds;
maskLayer.fillColor = [[UIColor blackColor] colorWithAlphaComponent:0.8].CGColor;
UIBezierPath *bezierPath=[UIBezierPath bezierPathWithRect:self.bounds];
[bezierPath appendPath:[[UIBezierPath bezierPathWithRoundedRect:alphaRect cornerRadius:cornerRadius] bezierPathByReversingPath]];
maskLayer.path = bezierPath.CGPath;
[self.layer insertSublayer:maskLayer atIndex:0];
}
}
@end
-
效果如图,透明位置可按需求改动.
redBorderMask.png
方法二:用CGContext在drawRect中绘制
绘制注意点:
1. GuideView的init方法中需要设置背景色为透明(否则制定透明部分不能正确显示), 即self.backgroundColor=[UIColor clearColor];
#define MLScreenH [UIScreen mainScreen].bounds.size.height
#define MLScreenW [UIScreen mainScreen].bounds.size.width
@implementation GuideView
- (instancetype)init{
self = [super init];
self.frame = CGRectMake(0, 0, MLScreenW, MLScreenH);
self.backgroundColor=[UIColor clearColor];
return self;
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
if (context == nil) {
return;
}
[[[UIColor blackColor] colorWithAlphaComponent:0.8f] setFill];
UIRectFill(rect);
[[UIColor clearColor] setFill];
//设置透明部分位置和圆角
CGRect alphaRect = CGRectMake(10, 100, 100, 100);
CGFloat cornerRadius = 10;
UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:alphaRect
cornerRadius:cornerRadius];
CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), [[UIColor clearColor] CGColor]);
CGContextAddPath(context, bezierPath.CGPath);
CGContextSetBlendMode(context, kCGBlendModeClear);
CGContextFillPath(context);
}
-
效果如图,透明位置可按需求改动.
drawRectMask.png