关于IOS下,将一组2DPoint连成平滑曲线的问题。

最近,在做一个项目的时候,利用跟踪TOUCH事件,捕获2D坐标点,并且将这些点连成平滑曲线,一开始简单的利用CGContextAddLines函数,简单的将各个坐标连起来,实际效果发现离预想效果要差很多。看下图:

                

应该看出效果了吧。左边的图画出来的轨迹一节节的,非常的不平滑,而右图好很多。其实这个地方是不能简单的将各个坐标点用CGContextAddLInes连起来,而是要用贝塞尔曲线。具体的代码如下:

(1)首先要写一个函数,获取2个点的中间点

-(CGPoint) midPointWithPoint1:(CGPoint) p1 Point2:(CGPoint) p2{
    return CGPointMake((p1.x + p2.x) * 0.5, (p1.y + p2.y) * 0.5);
}
(2)在touch事件中处理2D坐标

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    
    UITouch *touch = [touches anyObject];
    
    previousPoint1 = [touch previousLocationInView:self];
    previousPoint2 = [touch previousLocationInView:self];
    currentPoint = [touch locationInView:self];
    
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    
    UITouch *touch = [touches anyObject];
    
    previousPoint2 = previousPoint1;
    previousPoint1 = [touch previousLocationInView:self];
    currentPoint = [touch locationInView:self];
    
    
    // calculate mid point
    CGPoint mid1 = [self midPointWithPoint1:previousPoint1 Point2:previousPoint2];
    CGPoint mid2 = [self midPointWithPoint1:currentPoint Point2:previousPoint1];
    
    UIGraphicsBeginImageContext(self.frame.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [[UIColor blueColor]CGColor]);
    CGContextSetShouldAntialias(context, YES);
    CGContextSetAllowsAntialiasing(context, YES); //抗锯齿,用不用再说。
    CGContextSetFlatness(context, 0.1f);
    [self.imageView.image drawInRect:CGRectMake(0, 0, self.imageView.frame.size.width, self.imageView.frame.size.height)];
    
    CGContextMoveToPoint(context, mid1.x, mid1.y);
    // Use QuadCurve is the key
    CGContextAddQuadCurveToPoint(context, previousPoint1.x, previousPoint1.y, mid2.x, mid2.y); 
    
    CGContextSetLineCap(context, kCGLineCapRound);
    CGContextSetLineJoin(context, kCGLineJoinRound);
    CGContextSetLineWidth(context, 8.0);
    //CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);
    CGContextStrokePath(context);
    
    self.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
}
具体的实现就是这样了。在这里要非常感谢haoxiang,li,给了我比较大的帮助,在此把问题分享一下。


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值