首先创建了一个继承自UIView的LineView类,在storyboard中添加一个UIView,并把这个view的Custom Class属性设置为LineView

 

线的实现代码如下

- (void)drawRect:(CGRect)rect {

    // Drawing code

    //绘一条线

    

    //获取上下文 上下文的输出目标就是self.view

    CGContextRef context = UIGraphicsGetCurrentContext();

    

    //设置线的颜色

    CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1);

    

    //设置线宽

    CGContextSetLineWidth(context, 12);

    

    //设置线头尾的样式

    CGContextSetLineCap(context, kCGLineCapRound);

    

    //设置连接点的样式

    CGContextSetLineJoin(context, kCGLineJoinRound);

    

    //画一条线

    //设置起点

    CGContextMoveToPoint(context, 10, 10);

    

    //设置连线另一点

    CGContextAddLineToPoint(context, 20, 100);

    CGContextAddLineToPoint(context, 110, 10);

    

    //画到view [渲染]

    CGContextStrokePath(context);

    

}

 

矩形及三角形的实现代码

- (void)drawRect:(CGRect)rect {

    // Drawing code

    

    //[self drawRectangle];

    [self drawTriangle];

 

    

}

 

- (void)drawTriangle{

    

    //获取上下文

    CGContextRef context = UIGraphicsGetCurrentContext();

    

    //设置线的颜色

    CGContextSetRGBStrokeColor(context, 0.0, 1.0, 0.0, 1);

    

    //绘制一个点

    CGContextMoveToPoint(context, 10, 10);

    

    //绘制另外三个点

    CGContextAddLineToPoint(context, 110, 10);

    CGContextAddLineToPoint(context, 110, 110);

    //CGContextAddLineToPoint(context, 10, 10);

    

    //关闭路径

    CGContextClosePath(context);

    

    //渲染

    CGContextStrokePath(context);

}

 

- (void)drawRectangle{

 

    //绘一条线

    

    //获取上下文 上下文的输出目标就是self.view

    CGContextRef context = UIGraphicsGetCurrentContext();

    

    //设置线的颜色

    CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1);

    

    //设置线宽

    CGContextSetLineWidth(context, 5);

    

    

    //画一个矩形

    //=========第一种方法====================

    //    //设置起点

    //    CGContextMoveToPoint(context, 10, 10);

    //

    //    //设置连线另外三个点

    //    CGContextAddLineToPoint(context,110, 10);

    //    CGContextAddLineToPoint(context, 110, 110);

    //    CGContextAddLineToPoint(context, 10, 110);

    //    CGContextAddLineToPoint(context, 10, 10);

    

    //=========第一种方法====================

    

    CGContextAddRect(context, CGRectMake(10, 10, 100, 100));

    

    //画到view [渲染]

    

    //只是画一条 【空心】

    //CGContextStrokePath(context);

    

    //填充 【实心】

    CGContextFillPath(context);

 

}

 

 

posted on 2015-12-01 22:44  BansheeLw  阅读(188)  评论(0编辑  收藏  举报