【问题标题】:How to draw curved lines continuously in core graphics ios如何在核心图形ios中连续绘制曲线
【发布时间】:2016-12-28 12:34:36
【问题描述】:

在 iOS 应用程序中,我想绘制如下图所示的连续曲线。这是我的代码,但它只画了一条直线。

- (void)drawRect:(CGRect)rect{
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // set the line properties
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    CGContextSetLineCap(context, kCGLineCapRound);
    CGContextSetLineWidth(context, 30);
    CGContextSetAlpha(context, 0.6);
    
    // draw the line
    CGContextMoveToPoint(context, startPoint.x, startPoint.y);
    CGContextAddLineToPoint(context, endPoint.x, endPoint.y);
    CGContextStrokePath(context);
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    CGPoint current = [touch locationInView:self];
    startPoint=current;
    arrPoints=[[NSMutableArray alloc]init];
    [arrPoints addObject:NSStringFromCGPoint(startPoint)];
}

-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    CGPoint p = [touch locationInView:self];

    endPoint=p;
    [arrPoints addObject:NSStringFromCGPoint(endPoint)];
    [self setNeedsDisplay];
}

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self touchesMoved:touches withEvent:event];
}

这是我想要实现的图像,假设有五个视图,我想绘制从第一个视图到第二个、第三个等的连续线......同时我想在每个视图上绘制曲线排队。

【问题讨论】:

    标签: ios objective-c drawing core-graphics


    【解决方案1】:

    您的代码已经在构建一个点数组。

    现在你需要修改你的 drawRect 方法来在所有点之间绘制线段,而不仅仅是最新的。

    如果你从你的线段中构建一个UIBezierPath 并一次性绘制它,你可能会获得更好的性能。

    这样做的结果将是一系列近似曲线的连续短线段。如果用户快速移动手指,则线段会更长,使曲线看起来更不稳定。

    一旦你完成了这项工作,你就可以使用一些技术来平滑生成的曲线。 Erica Sadun 出色的“Core iOS 开发者食谱”有一个名为“Smoothing”的食谱,涵盖了这个主题。它完全符合您的要求 - 用户徒手绘制并平滑它。

    我在 Github 上有几个使用 Erica Sadun 的线条平滑技术的项目。

    项目KeyframeViewAnimations 绘制一条通过一组预定义点的曲线。

    项目“RandomBlobs”绘制了一条闭合曲线,它是多边形的平滑版本。

    这两个都包含了萨顿博士的曲线平滑代码,但同样,她书中的章节最适合您的需求。

    【讨论】:

    • 我想要实现的是假设有五个视图,我开始从一个视图绘制并在第二个视图移动线到另一个视图我想绘制手指移动方向的曲线
    • 根据您的描述,Erica Sadun 的“Core iOS Developer's cookbook”中“平滑绘图”配方中概述的平滑技术正是您想要的。它使用一种称为 Catmull-Rom 样条的技术从用户用手指绘制的点创建平滑曲线。我建议买那本书。它充满了像那个一样的宝石,而且那个“食谱”值这本书的价格,因为它完全符合您的要求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多