iOS 透明遮罩层
2017-06-09 本文已影响976人
Jesscia_Liu
-
有时候功能引导页需要对指定部分可见,其余为黑色遮罩.这时候需要用到图层绘制
-
注意点
- 封装的GuideView, 需要设置背景色为透明(否则制定透明部分不能正确显示)
- 在drawRect中设置封装的GuideView背景色为黑色,
然后设置透明范围(alphaRect)绘制透明部分
#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, 10, 100, 100);
CGFloat cornerRadius = 10;
UIBezierPath *bezierPath=[UIBezierPath bezierPathWithRoundedRect:alphaRect
cornerRadius:cornerRadius];
CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), [[UIColor clearColor] CGColor]);
CGContextAddPath(UIGraphicsGetCurrentContext(), bezierPath.CGPath);
CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeClear);
CGContextFillPath(UIGraphicsGetCurrentContext());
}
- 效果如图,透明位置可按需求改动.
![](https://img.haomeiwen.com/i4093812/47a7556635b36cf6.png)