引入了Core Graphices框架功能,演示如何画线条,文本,改变线条的额粗细,颜色,以及保存和恢复图形上下文。
要在一个视图中进行自定义绘制,我们必须首先获得当前图形上下文。图形上下文(CGContext)是一个绘图画布,它存放绘图信息,如颜色,线条宽度和字体。在调用drawRect:之前,由UIView配置当前图形上下文。UIGraphicsGetCurrentContext函数返回已经为当前UIView所配置的图形上下文。
2 | CGContextRef context = UIGraphicsGetCurrentContext(); |
5 | CGContextSaveGState(context); |
1 | /*通过调用CGContextRef中的CGContextTranslateCTM函数把坐标原点转换到左下角,该函数有两个参数,即水平和垂直方 |
1 | 向的变换数值。然后使用CGContextScaleCTM函数颠倒y轴,该函数有两个参数,即x轴和y轴的变换比例,第一个参数为1,保 |
1 | 持x轴不变,而第二个参数为-1,表示颠倒y轴*/ |
02 | CGContextTranslateCTM(context, 0, self.view.bounds.size.height); |
03 | CGContextScaleCTM(context, 1.0, -1.0); |
06 | NSString *str = [NSString stringWithFormat:@ "Time remaining:%i seconds" , timeLeft]; |
09 | CGContextSelectFont(context, "Helvetica" , 16, kCGEncodingMacRoman); |
10 | CGContextSetTextDrawingMode(context, kCGTextFill); |
13 | CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, 1.0); |
16 | CGContextShowTextAtPoint(context, 10.0, 10.0, [str cStringUsingEncoding:[NSString defaultCStringEncoding]], str.length); |
17 | CGContextRestoreGState(context); |
20 | if (cannonballOnScreen) |
23 | CGRect cannonballRect = CGRectMake(cannonball.x, cannonball.y, CANNON_BASE_RADIUS * 2, CANNON_BASE_RADIUS * 2); |
24 | UIImage *image = [UIImage imageNamed:@ "cannonball80.png" ]; |
27 | CGContextDrawImage(context, cannonballRect, image.CGImage); |
32 | CGContextMoveToPoint(context, 0 , self.view.frame.size.height / 2); |
35 | CGContextAddLineToPoint(context, barrelEnd.x , barrelEnd.y); |
36 | CGContextSetLineWidth(context, 20); |
37 | CGContextSetRGBStrokeColor(context, 0.0, 0.0, 0.0, 1.0); |
38 | CGContextStrokePath(context); |
41 | CGRect cannonBase = CGRectMake(0, self.view.frame.size.height / 2 - CANNON_BASE_RADIUS, CANNON_BASE_RADIUS, CANNON_BASE_RADIUS * 2); |
44 | UIImage *baseImage = [UIImage imageNamed:@ "cannon_base.png" ]; |
47 | CGContextDrawImage(context, cannonBase, baseImage.CGImage); |
50 | CGContextMoveToPoint(context, blocker.start.x, blocker.start.y); |
51 | CGContextAddLineToPoint(context, blocker.end.x, blocker.end.y); |
52 | CGContextSetLineWidth(context, LINE_WIDTH); |
54 | CGContextStrokePath(context); |
57 | float pieceLength = (TARGET_END - TARGET_BEGINING) / TARGET_PIECES; |
60 | CGContextMoveToPoint(context, target.start.x, target.start.y); |
63 | for ( int i = 1; i <= TARGET_PIECES; i++) |
68 | CGContextSetRGBStrokeColor(context, 1, 1, 0, 1); |
72 | CGContextSetRGBStrokeColor(context, 0, 0, 0.5, 1); |
76 | CGContextMoveToPoint(context, target.end.x, target.start.y + pieceLength * (i - 1)); |
79 | if (!targetPieceHit[i - 1]) |
82 | CGContextAddLineToPoint(context, target.end.x, target.start.y + pieceLength * i); |
83 | CGContextStrokePath(context); |