1 #import <UIKit/UIKit.h>
2
3 @interface NJLineView : UIView
4 @end
5
6
7 #import "NJLineView.h"
8
9 @implementation NJLineView
10
11 // 当自定义view第一次显示出来的时候就会调用drawRect方法
12 - (void)drawRect:(CGRect)rect
13 {
14 // 1.取得和当前视图相关联的图形上下文(因为图形上下文决定绘制的输出目标)/
15
16 // 如果是在drawRect方法中调用UIGraphicsGetCurrentContext方法获取出来的就是Layer的上下文
17 CGContextRef ctx = UIGraphicsGetCurrentContext();
18
19 // 2.绘图(绘制直线), 保存绘图信息
20 // 设置起点
21 CGContextMoveToPoint(ctx, 10, 100);
22 // 设置终点
23 CGContextAddLineToPoint(ctx, 100, 100);
24
25 // 设置绘图状态
26 // 设置线条颜色 红色
27 CGContextSetRGBStrokeColor(ctx, 1.0, 0, 0, 1.0);
28 // 设置线条宽度
29 CGContextSetLineWidth(ctx, 10);
30 // 设置线条的起点和终点的样式
31 CGContextSetLineCap(ctx, kCGLineCapRound);
32 // 设置线条的转角的样式
33 CGContextSetLineJoin(ctx, kCGLineJoinRound);
34 // 绘制一条空心的线
35 CGContextStrokePath(ctx);
36
37 /*------------------华丽的分割线---------------------*/
38
39 // 重新设置第二条线的起点
40 CGContextMoveToPoint(ctx, 150, 200);
41 // 设置第二条直线的终点(自动把上一条直线的终点当做起点)
42 CGContextAddLineToPoint(ctx, 100, 50);
43 // 设置第二条线的颜色 绿色
44 // [[UIColor greenColor] set];
45 CGContextSetRGBStrokeColor(ctx, 0, 1.0, 0, 1.0);
46
47 // 绘制图形(渲染图形到view上)
48 // 绘制一条空心的线
49 CGContextStrokePath(ctx);
50
51 }
52
53 @end
![]()