對CALayer繼承,CALayer重新繪制時(shí)助隧,執(zhí)行的方法:
- (void)drawInContext:(CGContextRef)ctx
當(dāng)需要用UIBezierPath繪制圖形時(shí)唆香,直接設(shè)置是無效的嫌变,要對ctx進(jìn)行呀站操作:
UIGraphicsPushContext(ctx);
執(zhí)行完繪制要對上下文進(jìn)行pop操作:
UIGraphicsPopContext();
layer上繪制一個(gè)中空的圓形代碼如下:
- (void)drawInContext:(CGContextRef)ctx {
UIGraphicsPushContext(ctx);
//創(chuàng)建圓形框UIBezierPath:
UIBezierPath *pickingFieldPath = [UIBezierPath bezierPathWithOvalInRect:self.maskRect];
//創(chuàng)建外圍大方框UIBezierPath:
UIBezierPath *bezierPathRect = [UIBezierPath bezierPathWithRect:self.bounds];
//將圓形框path添加到大方框path上去,以便下面用奇偶填充法則進(jìn)行區(qū)域填充:
[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;
}