#define MJColor(r,g,b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]
1.自定义一个MJHumanView,默认View的Class设置为MJHumanView
2.实现drawRect:方法-(void)drawRect:(CGRect)rect{//1.上下文CGContextRef ctx = UIGraphicsGetCurrentContext();//2.身体drawBody(ctx,rect);//3.嘴(微笑)drawMouth(ctx,rect);//4.画眼睛drawEyes(ctx,rect);}
二、画身体
//画身体void drawBody(CGContextRef ctx,CGRect rect){//上半圆CGFloat topX = rect.size.width *0.5;CGFloat topY = MJTopY;CGFloat topRadius = MJRadius; //半径因为经常要用,所以设为宏CGContextAddArc(ctx,topX,topY,topRadius,0,M_PI,1);//向下延伸CGFloat middleX = topX - topRadius;CGFloat middleH = 100; //中间的身体长度CGFloat middleY = topY + middleH;CGContextAddLineToPoint(ctx,middleX,middleY);//下半圆CGFloat bottomX = topX;CGFloat bottomY = middleY;CGFloat bottomRadius = topRadius;CGContextAddArc(ctx,bottomX,bottomY,bottomRadius,M_PI,0,1); //合并路径CGContextClosePath(ctx);//设置颜色(写成了宏)[MJColor(252,218,0) set];//利用填充方式画出之前的路径CGContextFillPath(ctx);}
三、画嘴巴
void drawMouth(CGContextRef ctx,CGRect rect){//中间的控制点CGFloat controlX = rect.size.width * 0.5;CGFloat controlY = rect.size.height * 0.4;//当前点CGFloat marginX = 20;//控制点与2点在X方向上的间距,越大则越长CGFloat marginY = 10;//控制点与2点在Y方向上的间距,越大则越尖CGFloat currentX = controlX - marginX;CGFloat currentY = controlY - marginY; CGContextMoveToPoint(ctx,currentX,currentY);//结束点CGFloat endX = controlX + marginX;CGFloat endY = currentY;//贝塞尔曲线CGContextAddQuadCurveToPoint(controlX,controlY,endX,endY);//设置颜色[[UIColor blackColor] set];//渲染CGContextStrokePath(ctx);}
四、画眼睛
void drawEyes(CGContextRef ctx,CGRect rect){//1.画黑色绑带CGFloat startX = rect.size.width * 0.5 - MJRadius;CGFloat startY = MJTopY;CGContextMoveToPoint(ctx,startX,startY);CGFloat endX = start +2 * MJRadius;CGFloat endY = startY;CGContextAddLineToPoint(ctx,endX,endY);CGContextSetLineWidth(ctx,15);[[UIColor blackColor] set];//绘制线条CGontextStrokePath(ctx);//2.画最外圈的镜框[MJColor(61,62,66) set];CGFloat frameRadius = MJRadius * 0.4;CGFloat frameY = startY;CGFloat frameX = rect.size.width * 0.5 - MJRadius;CGContextAddArc(ctx,frameX,frameY,frameRadius,0,M_PI * 2,0); CGContextFillPath(ctx);//3.画里面的白色框[[UIcolor whiteColor] set];CGFloat whiteRadius = frameRadius * 0.7;CGFloat whiteY = frameY;CGFloat whiteX =frameX;CGContextAddArc(ctx,whiteX,whiteY,whiteRadius,0,M_PI * 2,0); CGContextFillPath(ctx);//眼珠同理}