39.两种定时器 CGPath 画四边形 UIBezierPath


// NSTimer一般用于定时的更新一些非界面上的数据
[NSTimer scheduledTimerWithTimeInterval:
         0.1 target:self selector:@selector(updataImage) userInfo:nil repeats:YES];

// 创建CADisplayLink, 默认每秒60次
CADisplayLink *display = [CADisplayLink displayLinkWithTarget:self selector:@selector(updataImage)];
// 将CADisplayLink加入到消息循环中
[display addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
- (void)drawRect:(CGRect)rect
{
    // 1.获取上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    // 2.绘制图形
    /*
    // 设置起点
    CGContextMoveToPoint(ctx, 10, 10);
    // 设置终点
    CGContextAddLineToPoint(ctx, 100, 100);

    // 3.画圆
    CGContextAddEllipseInRect(ctx, CGRectMake(50, 50, 50, 50));
    */


    // 2.创建路径(一个path就代表一条路径)
    // 但凡通过quarzt2d中的带有create/ copy / retain 方法创建出来的值都必须手动的释放
    CGMutablePathRef path = CGPathCreateMutable();
    // 设置起点
    CGPathMoveToPoint(path, NULL, 10, 10);
    // 设置终点
    CGPathAddLineToPoint(path, NULL, 100, 100);
    // 将路径添加到上下文中
    CGContextAddPath(ctx, path);

    // 3.再创建一条路径用于保存圆
     CGMutablePathRef path2 = CGPathCreateMutable();
    // 在path中添加画的路径
    CGPathAddEllipseInRect(path2, NULL, CGRectMake(50, 50, 50, 50));
    CGContextAddPath(ctx, path2);

    // 3.渲染'
    CGContextStrokePath(ctx);


    // 释放前面创建的两条路径
    CGPathRelease(path);
    CGPathRelease(path2);

    // 下面这种方式也可以释放路径

    CFRelease(path);
    CFRelease(path2);


UIBezierPath是OC方法,用法和CGPath类似,使用更为简单
    UIBezierPath *bezier = [UIBezierPath bezierPath];
    [bezier moveToPoint:point];
    [bezier addLineToPoint:point];
    [bezier stroke];
}
- (void)test
{
    // 画四边形
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    //    1.第一种方式, 通过连接固定的点绘制四边形
    //    CGContextMoveToPoint(ctx, 0, 0);
    //    CGContextAddLineToPoint(ctx, <#CGFloat x#>, <#CGFloat y#>)
    //    CGContextAddLineToPoint(ctx, <#CGFloat x#>, <#CGFloat y#>)
    //    CGContextAddLineToPoint(ctx, <#CGFloat x#>, <#CGFloat y#>)
    //    CGContextAddLineToPoint(ctx, <#CGFloat x#>, <#CGFloat y#>)


    //    2.指定起点和宽高绘制四边形
    //    CGContextAddRect(ctx, CGRectMake(10, 10, 100, 100));
    //    CGContextStrokePath(ctx);

    // 3.两步合为一部
    //    CGContextStrokeRect(ctx, CGRectMake(10, 10, 100, 100));
    //    CGContextFillRect(ctx, CGRectMake(10, 10, 100, 100));

    // 4.通过OC的方法绘制实心的四边形, 注意没有空心的方法
    //    UIRectFill(CGRectMake(10, 10, 100, 100));

    // 5.通过绘制线条设置宽度
    CGContextMoveToPoint(ctx, 10, 10);
    CGContextAddLineToPoint(ctx, 100, 100);
    CGContextSetLineWidth(ctx, 50);
    CGContextStrokePath(ctx);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值