转自:http://blog.sina.com.cn/s/blog_79a120e501018c2n.html
UIView 的方法:
- (void)drawRect:(CGRect)rect
获取当前context:
CGContextRef context =UIGraphicsGetCurrentContext();
获取当前bounds的起点和size:
self.bounds.origin
self.bounds.size
设置画图的线宽和填充线的颜色:
CGContextSetLineWidth(context, 5.0);
[[UIColor blueColor]setStroke];
画图另外调用方法:
在用context之前需要push下,最后再pop,这样就不会破坏外面的context,随便我在里面做什么。
UIGraphicsPushContext(context);
CGContextBeginPath(context);
CGContextAddArc(context, p.x,p.y, radius, 0, 2*M_PI,YES);
//CGContextAddCurveToPoint(context,mouthCP1.x, mouthCP1.y,mouthCP2.x, mouthCP2.y,//mouthEnd.x, mouthEnd.y);都是一样的套路。。
CGContextStrokePath(context);
UIGraphicsPopContext();
继承uiview,将uiview变成子view。UIBezierPath类画图。是用矩形坐标画图的
- (void)drawRect:(CGRect)rect
{
//矩形画图区域
CGRect aRectangle = CGRectMake(0.0, 0.0, 40.0, 40.0);
//定义一个矩形路径
UIBezierPath *path =[UIBezierPath bezierPathWithRect:aRectangle];
//将矩形路径画出来
[pathstroke];
//在区域中画一个椭圆
path = [UIBezierPathbezierPathWithOvalInRect:aRectangle];
//椭圆填充
[pathfill];
//定义一个开始路径
UIBezierPath *startPath= [UIBezierPath bezierPath];
//开始画五角星
[startPathmoveToPoint:CGPointMake(40.0, 0.0)];
[startPath addLineToPoint:CGPointMake(30.0, 30.0)];
[startPath addLineToPoint:CGPointMake(0.0, 30.0)];
[startPath addLineToPoint:CGPointMake(20.0, 50.0)];
[startPath addLineToPoint:CGPointMake(10.0, 80.0)];
[startPath addLineToPoint:CGPointMake(40.0, 60.0)];
[startPath addLineToPoint:CGPointMake(70.0, 80.0)];
[startPath addLineToPoint:CGPointMake(60.0, 50.0)];
[startPath addLineToPoint:CGPointMake(80.0, 30.0)];
[startPath addLineToPoint:CGPointMake(50.0, 30.0)];
[startPathclosePath];
//获取当前环境
CGContextRef context= UIGraphicsGetCurrentContext();
//保存当前环境,便于以后恢复
CGContextSaveGState(context);
//将坐标的起点变成(100,100)
CGContextTranslateCTM(context, 100, 100);
//将当前的颜色变成黄色
UIColor* fillColor =[UIColor yellowColor];
[fillColorsetFill];
//五角星填充为黄色
[startPathfill];
//将坐标起点变成(100,100)开始,注意:这里是当前的(100,100)的相对位移,所以相对整个view是(200,200)
CGContextTranslateCTM(context, 100, 100);
//将坐标旋转45度
CGContextRotateCTM(context, 3.14/4);
//将当前颜色变成绿色
fillColor =[UIColor greenColor];
[fillColorsetFill];
//将五角星的轮廓画上颜色
[startPathstroke];
//五角星填充
[startPathfill];
//恢复context,当然,是恢复成之前保存的那个
CGContextRestoreGState(context);
//将当前context保存
CGContextSaveGState(context);
CGContextTranslateCTM(context, 50, 250);
[startPathfill];
CGContextRestoreGState(context);
}