您的位置:首页 > 移动开发 > IOS开发

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

2012-03-11 10:16 447 查看
最近,在做一个项目的时候,利用跟踪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,给了我比较大的帮助,在此把问题分享一下。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: