通过drawRect 我们可以绘制各种图形、线条,这里介绍绘制直线的方法
- (void) drawLineFrom:(CGPoint) fromPoint toPoint:(CGPoint) toPoint lineWidth:(CGFloat) lineWidth lineColor:(UIColor*) lineColor {
CGContextRef context = UIGraphicsGetCurrentContext();
//指定直线样式
CGContextSetLineCap(context,kCGLineCapButt);
//直线宽度
CGContextSetLineWidth(context, lineWidth);
//设置颜色
// CGContextSetRGBStrokeColor(context, .5, .4, .3, 1.0);
CGContextSetStrokeColorWithColor(context, lineColor.CGColor);
//开始绘制
CGContextBeginPath(context);
CGContextMoveToPoint(context,fromPoint.x, fromPoint.y);
CGContextAddLineToPoint(context,toPoint.x, toPoint.y);
//绘制完成
CGContextStrokePath(context);
}
上面的方法绘制点到点的直线,线条的宽度,颜色都由自己设置。
可以在drawRect里面测试,如:
- (void)drawRect:(CGRect)rect
{
UIColor* lineColor = COLOR(226, 226, 226);
[self drawLineFrom:CGPointMake(0, self.frame.size.height/2) toPoint:CGPointMake(self.frame.size.width, self.frame.size.height/2) lineWidth:1 lineColor:lineColor];
[self drawLineFrom:CGPointMake(self.frame.size.width/2, 0) toPoint:CGPointMake(self.frame.size.width/2, self.frame.size.height) lineWidth:1 lineColor:lineColor];
}