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

运行结果截图

转载于:https://www.cnblogs.com/wlxm/p/4295130.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值