6. Quartz2D 随机绘制N个五角星
#import "MyView.h" #pragma mark - 记录五角星5个顶点 CGPoint points[5]; @interface MyView(){ //判断是否已经计算过顶点 BOOL _hasPoint; } @end @implementation MyView -(void) drawRect:(CGRect)rect{ if (!_hasPoint) { //计算五个角 [self loadPoints]; _hasPoint = YES; } CGContextRef context = UIGraphicsGetCurrentContext(); [self drawRandomStarWithContext:context count:10]; } #pragma mark - 计算五角星初始数组 -(void) loadPoints{ //半径 CGFloat r = 100; // 第一个点 points[0] = CGPointMake(0, -r); //旋转角度 CGFloat angle = 4 * M_PI / 5; for (int i=1; i<5; i++) { //下一目标点的坐标 CGFloat x = cosf(i*angle - M_PI_2) * r; CGFloat y = sinf(i*angle - M_PI_2) * r; points[i] = CGPointMake(x, y); } } #pragma mark 随机颜色 - (UIColor *) randomColor{ CGFloat r = arc4random_uniform(255) / 255.0; CGFloat g = arc4random_uniform(255) / 255.0; CGFloat b = arc4random_uniform(255) / 255.0; return [UIColor colorWithRed:r green:g blue:b alpha:1.0]; } #pragma mark 随机绘制N个五角星 -(void)drawRandomStarWithContext:(CGContextRef)context count:(NSInteger)count{ for (NSInteger i = 0; i<count; i++) { //保存上下文 CGContextSaveGState(context); //平移上下文 CGFloat x = arc4random()%320; CGFloat y = arc4random()%460; CGContextTranslateCTM(context, x, y); //旋转上下文 CGFloat scale = arc4random_uniform(10) / 10.0 + 0.5; CGContextScaleCTM(context, scale, scale); //缩放上下文 CGFloat angle = (arc4random() % 180) *M_PI / 180; CGContextRotateCTM(context, angle); [self drawStar:context ]; //恢复上下文 CGContextRestoreGState(context); } } #pragma mark 绘制五角星方法 -(void) drawStar:(CGContextRef)context{ [[self randomColor]set]; //设置起点 CGContextMoveToPoint(context, points[0].x, points[0].y); for (int i=1; i< 5; i++) { CGContextAddLineToPoint(context, points[i].x, points[i].y); } CGContextClosePath(context); CGContextDrawPath(context, kCGPathFill); } @end
运行结果截图