#define MJColor(r,g,b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]
1.自定义一个MJHumanView,继承自UIView
2.默认View(整一个View)的Class设置为MJHumanView
3.实现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);
PS:眼珠同理
}