学习了Quartz2D后,练习着画了个简单的小黄人,分享一下代码
自定义一个继承于UIView的视图,调用drawRect方法:
#import "HumenView.h"#define color(r,g,b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1]@implementation HumenView- (void)drawRect:(CGRect)rect{ CGContextRef ctx = UIGraphicsGetCurrentContext(); //身体 //上半圆 CGFloat topCicleX = rect.size.width/2; CGFloat topCicleY = 150; CGFloat topradius = 70; CGContextAddArc(ctx, topCicleX, topCicleY, topradius, 0,M_PI, 1); //向下延伸 CGFloat middleX = topCicleX - topradius; CGContextAddLineToPoint(ctx, middleX, topCicleY + 100); CGContextAddArc(ctx, topCicleX, topCicleY + 100, topradius, M_PI, 0, 1); CGContextClosePath(ctx); //设置颜色 [color(252, 218, 0)setFill]; CGContextFillPath(ctx); //画嘴 控制点 CGFloat controlX = rect.size.width/2; CGFloat controlY = rect.size.height/3; CGFloat marginX = 30; CGFloat marginY = 20; CGFloat currentX = controlX - marginX; CGFloat currentY = controlY - marginY; CGContextMoveToPoint(ctx, currentX, currentY); CGFloat endX = controlX + marginX; CGFloat endY = currentY; [[UIColor blackColor]set]; CGContextAddQuadCurveToPoint(ctx, controlX, controlY, endX, endY); CGContextStrokePath(ctx); //画眼睛 //绑带 CGContextMoveToPoint(ctx, middleX, topCicleY); CGContextAddLineToPoint(ctx, middleX+topradius*2, topCicleY); CGContextSetLineWidth(ctx, 20); [[UIColor blackColor]setStroke]; CGContextStrokePath(ctx); //最外的镜框 CGFloat radius = topradius *0.4; CGFloat kuangX = topCicleX - radius; CGFloat kuangY = topCicleY; //左边 CGContextAddArc(ctx, kuangX, kuangY, radius, 0, M_PI*2, 1); [[UIColor lightGrayColor]set]; CGContextFillPath(ctx); // 右边 CGContextAddArc(ctx, topCicleX + radius, kuangY, radius, 0, M_PI*2, 1); [[UIColor lightGrayColor]set]; CGContextFillPath(ctx); //白色镜框 CGContextAddArc(ctx, topCicleX - radius, kuangY, radius*0.7, 0, M_PI*2, 1); [[UIColor whiteColor]set]; CGContextFillPath(ctx); CGContextAddArc(ctx, topCicleX + radius, kuangY, radius*0.7, 0, M_PI*2, 1); [[UIColor whiteColor]set]; CGContextFillPath(ctx); //眼珠 CGFloat eyeRadius = 10; CGFloat eyeX = topCicleX - eyeRadius - 10; CGFloat eyeY = kuangY; CGContextAddArc(ctx, eyeX, eyeY, eyeRadius, 0, M_PI*2, 1); [color(66,25,11)set]; CGContextFillPath(ctx); CGContextAddArc(ctx, topCicleX + eyeRadius + 10, eyeY, eyeRadius, 0, M_PI*2, 1); [color(66,25,11)set]; CGContextFillPath(ctx);}@end