CALayer之drawInContext:(绘制中空的图形)
2017-09-12 本文已影响98人
LX2014
对CALayer继承,CALayer重新绘制时,执行的方法:
- (void)drawInContext:(CGContextRef)ctx
当需要用UIBezierPath绘制图形时,直接设置是无效的,要对ctx进行呀站操作:
UIGraphicsPushContext(ctx);
执行完绘制要对上下文进行pop操作:
UIGraphicsPopContext();
layer上绘制一个中空的圆形代码如下:
- (void)drawInContext:(CGContextRef)ctx {
UIGraphicsPushContext(ctx);
//创建圆形框UIBezierPath:
UIBezierPath *pickingFieldPath = [UIBezierPath bezierPathWithOvalInRect:self.maskRect];
//创建外围大方框UIBezierPath:
UIBezierPath *bezierPathRect = [UIBezierPath bezierPathWithRect:self.bounds];
//将圆形框path添加到大方框path上去,以便下面用奇偶填充法则进行区域填充:
[bezierPathRect appendPath:pickingFieldPath];
[[[UIColor blackColor] colorWithAlphaComponent:0.5] set];
//填充使用奇偶法则
bezierPathRect.usesEvenOddFillRule = YES;
[bezierPathRect fill];
[[UIColor whiteColor] set];
[pickingFieldPath setLineWidth:2];
[pickingFieldPath stroke];
UIGraphicsPopContext();
self.contentsGravity = kCAGravityCenter;
}