写在前面
在开发的过程中,偶尔会遇到需要在引导图上进行 镂空、画虚线,找了一下资料,写了下工具类,具体实现的效果如下。
ZZHollowUtil.h文件
#import <Foundation/Foundation.h>
/**
这个类用来镂空UIView,并且在镂空部分边缘添加虚线
注意: 一个UIView 只能调用一次 -addHollowWithPath:inView: ,否则会有冲突,显示效果上会有问题
建议: 将需要镂空的路径,用UIBezierPath 的 -appendPath: 方法加在一起,再调用。
-addLineWithCGPath:inView: 可以多次调用
例如:
UIBezierPath *path = [UIBezierPath bezierPath];
[path appendPath:path_0];
[path appendPath:path_1];
[ZZHollowUtil addHollowWithPath:path inView:self];
[ZZHollowUtil addLineWithCGPath:path_1.CGPath inView:self];
[ZZHollowUtil addLineWithCGPath:path_2.CGPath inView:self];
*/
@interface ZZHollowUtil : NSObject
// 镂空
+ (void)addHollowWithPath:(UIBezierPath *)path inView:(UIView *)view;
// 画虚线 默认:黑白相间
+ (void)addLineWithCGPath:(CGPathRef)path inView:(UIView *)view;
+ (void)addLineWithCGPath:(CGPathRef)path
stockerColor:(UIColor *)stokerColor
fillColor:(UIColor *)fillColor
inView:(UIView *)view;
@end
ZZHollowUtil.m文件
#import "ZZHollowUtil.h"
@implementation ZZHollowUtil
+ (void)addHollowWithPath:(UIBezierPath *)path inView:(UIView *)view {
dispatch_async(dispatch_get_main_queue(), ^{
UIBezierPath *aPath = [UIBezierPath bezierPathWithRect:view.bounds];
[aPath appendPath:[path bezierPathByReversingPath]];
//创建出CAShapeLayer
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
//让贝塞尔曲线与CAShapeLayer产生联系
shapeLayer.path = aPath.CGPath;
//添加并显示
[view.layer setMask:shapeLayer];
});
}
+ (void)addLineWithCGPath:(CGPathRef)path inView:(UIView *)view {
[self addLineWithCGPath:path
stockerColor:[UIColor whiteColor]
fillColor:[UIColor blackColor]
inView:view];
}
+ (void)addLineWithCGPath:(CGPathRef)path
stockerColor:(UIColor *)stokerColor
fillColor:(UIColor *)fillColor
inView:(UIView *)view
{
CAShapeLayer *border = [CAShapeLayer layer];
border.strokeColor = stokerColor.CGColor;
border.fillColor = fillColor.CGColor;
border.path = path;
border.frame = view.bounds;
border.lineWidth = 2.f;
border.lineCap = @"square";
border.lineDashPattern = @[@6, @4];
[view.layer addSublayer:border];
}
@end
如果有遇到问题,在下边评论,第一时间回复。
如果有更好的实现方式,欢迎讨论。