iOS 利用 CAShapeLayer 的 FillRule 属性生成一个空心遮罩的 Layer

1.空心矩形框:
通过设置填充规则为 kCAFillRuleEvenOdd,绘制两个 Rect 的非交集

UIView aView = [[UIView alloc] initWithFrame:CGRectMake(100,80, 100, 100)];
[self.view addSubview:aView];
//用来标识layer的绘图是否正确
aView.layer.borderWidth = 1.0;
aView.layer.borderColor = [UIColor blackColor].CGColor;
CAShapeLayer cropLayer = [[CAShapeLayer alloc] init];
[aView.layer addSublayer:cropLayer];
// 创建一个绘制路径
CGMutablePathRef path =CGPathCreateMutable();
// 空心矩形的rect
CGRect cropRect = CGRectMake(20, 30, 60, 40);
// 绘制rect
CGPathAddRect(path, nil, aView.bounds);
CGPathAddRect(path, nil, cropRect);
// 设置填充规则(重点)
[cropLayer setFillRule:kCAFillRuleEvenOdd];
// 关联绘制的path
[cropLayer setPath:path];
// 设置填充的颜色
[cropLayer setFillColor:[[UIColor redColor] CGColor]];


效果图 :
[img]http://dl2.iteye.com/upload/attachment/0122/0661/3abebb49-c86b-348b-bbf0-a2e534a2963b.jpg[/img]
2.空心圆:
通过设置填充规则为kCAFillRuleEvenOdd,绘制Rect和Arc的非交集

CAShapeLayer *pShapeLayer = [CAShapeLayer layer];
pShapeLayer.fillColor = [UIColor blackColor].CGColor;[self.overlayView.layer addSublayer:pShapeLayer];UIBezierPath *pPath = [UIBezierPath bezierPathWithArcCenter:self.overlayView.center radius:SCALE_FRAME_Y/2 startAngle:0.0 endAngle:M_PI*2 clockwise:YES];
pShapeLayer.path = pPath.CGPath;

UIBezierPath *pOtherPath = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
pShapeLayer.path = pOtherPath.CGPath;

[pOtherPath appendPath:pPath];
pShapeLayer.path = pOtherPath.CGPath;
//重点
pShapeLayer.fillRule = kCAFillRuleEvenOdd;

效果图:
[img]http://dl2.iteye.com/upload/attachment/0122/0663/012f3169-210d-374f-9636-86a1b051d758.jpg[/img]
/* The fill rule used when filling the path. Options are `non-zero' and
[list]
[*]even-odd'. Defaults to
non-zero'. /@property(copy) NSString fillRule;属性用于指定使用哪一种算法去判断画布上的某区域是否属于该图形“内部” (内部区域将被填充)。对一个简单的无交叉的路径,哪块区域是“内部” 是很直观清除的。但是,对一个复杂的路径,比如自相交或者一个子路径包围另一个子路径,“内部”的理解就不那么明确了。
[/list]
kCAFillRuleNonZero

字面意思是“非零”。按该规则,要判断一个点是否在图形内,从该点作任意方向的一条射线,然后检测射线与图形路径的交点情况。从0开始计数,路径从左向右穿过射线则计数加1,从右向左穿过射线则计数减1。得出计数结果后,如果结果是0,则认为点在图形外部,否则认为在内部。下图演示了kCAFillRuleNonZero规则:
[img]http://dl2.iteye.com/upload/attachment/0122/0665/df061598-fbe9-3137-8093-5ad54a6ad49b.jpg[/img]
kCAFillRuleEvenOdd
字面意思是“奇偶”。按该规则,要判断一个点是否在图形内,从该点作任意方向的一条射线,然后检测射线与图形路径的交点的数量。如果结果是奇数则认为点在内部,是偶数则认为点在外部。下图演示了kCAFillRuleEvenOdd 规则:
[img]http://dl2.iteye.com/upload/attachment/0122/0667/4900f8c7-a725-33a0-ba5c-d80e74dbea5e.jpg[/img]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值