下面是矩形的各种画法:
-(void)drawInContext:(CGContextRef)context{
//线条的颜色
CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
//填充图形的颜色
CGContextSetFillColorWithColor(context, [UIColor blueColor].CGColor);
CGContextSetLineWidth(context, 2.0);
//添加一个矩形
CGContextAddRect(context, CGRectMake(30.0, 30.0, 60.0, 60.0));
//画出图形线条,这个方法是对画出的图形不填充
CGContextStrokePath(context);
//画出一个矩形,和上面的一样
CGContextStrokeRect(context, CGRectMake(30.0, 120.0, 60.0, 60.0));
//画出一个带自定义线条宽度的矩形
CGContextStrokeRectWithWidth(context, CGRectMake(30.0, 210.0, 60.0, 60.0), 10.0);
//保存上下文,在Save和restore内的部分,对以后没有影响
CGContextSaveGState(context);
CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);
CGContextStrokeRectWithWidth(context, CGRectMake(30.0, 210.0, 60.0, 60.0), 2.0);
CGContextRestoreGState(context);
//一下画多个矩形
CGRect rects[] =
{
CGRectMake(120.0, 30.0, 60.0, 60.0),
CGRectMake(120.0, 120.0, 60.0, 60.0),
CGRectMake(120.0, 210.0, 60.0, 60.0),
};
CGContextAddRects(context, rects, sizeof(rects)/sizeof(rects[0]));
CGContextStrokePath(context);
//添加一个矩形,是填充的哦。
CGContextAddRect(context, CGRectMake(210.0, 30.0, 60.0, 60.0));
CGContextFillPath(context);
//简便方法,直接一个填充矩形
CGContextFillRect(context, CGRectMake(210.0, 120.0, 60.0, 60.0));
}
画直线的各种方法
//画一条普通的直线
CGContextMoveToPoint(context, 10.0, 30.0);
CGContextAddLineToPoint(context, 310.0, 30.0);
CGContextStrokePath(context);
//一次画很多直线,下一条直线的开始是上一条直线的结尾
CGPoint addLines[] =
{
CGPointMake(10.0, 90.0),
CGPointMake(70.0, 60.0),
CGPointMake(130.0, 90.0),
CGPointMake(190.0, 60.0),
CGPointMake(250.0, 90.0),
CGPointMake(310.0, 60.0),
};
// 相当于 for(i=1; i<count; ++i) AddLineToPoint(points[i]);
CGContextAddLines(context, addLines, sizeof(addLines)/sizeof(addLines[0]));
CGContextStrokePath(context);
// 画一系列的直线片段,每两个点配对成一条直线
CGPoint strokeSegments[] =
{
CGPointMake(10.0, 150.0),
CGPointMake(70.0, 120.0),
CGPointMake(130.0, 150.0),
CGPointMake(190.0, 120.0),
CGPointMake(250.0, 150.0),
CGPointMake(310.0, 120.0),
};
// 相当于for(i=0; i<count; i+=2) { MoveToPoint(point[i]); AddLineToPoint(point[i+1]); StrokePath(); }
CGContextStrokeLineSegments(context, strokeSegments, sizeof(strokeSegments)/sizeof(strokeSegments[0]));