关于IOS下,将一组2DPoint连成平滑曲线的问题。
2012-03-11 10:16
447 查看
最近,在做一个项目的时候,利用跟踪TOUCH事件,捕获2D坐标点,并且将这些点连成平滑曲线,一开始简单的利用CGContextAddLines函数,简单的将各个坐标连起来,实际效果发现离预想效果要差很多。看下图:
应该看出效果了吧。左边的图画出来的轨迹一节节的,非常的不平滑,而右图好很多。其实这个地方是不能简单的将各个坐标点用CGContextAddLInes连起来,而是要用贝塞尔曲线。具体的代码如下:
(1)首先要写一个函数,获取2个点的中间点
应该看出效果了吧。左边的图画出来的轨迹一节节的,非常的不平滑,而右图好很多。其实这个地方是不能简单的将各个坐标点用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,给了我比较大的帮助,在此把问题分享一下。
相关文章推荐
- iOS 关于presentViewController弹出页面反应迟钝的问题
- 【IOS学习之常见问题】 关于IOS证书的那点折腾事2-百科证书
- iOS指南系列:关于进度条的问题
- iOS 关于presentViewController弹出页面反应迟钝的问题
- 关于16年2月14日以后上传AppStore出现:Missing iOS Distribution signing identity for...的问题
- 关于iOS中网络请求汉字转码问题
- iOS开发笔记--关于设置UIView的背景为图片的方法以及问题
- iOS 关于tabbar点击navigationcontroller root到根视图的问题解决办法
- 关于ios发布AppStore验证UUID不过的问题
- iOS关于iPhone6和iPhone6 Plus的屏幕适配问题
- 关于Xcode8.1 / iOS10+ 真机测试系统打印或者宏定义打印不显示问题
- 关于iOS5 + XCode4.2环境下iPhone3G和3Gs + iOS4.2.1不能调试的问题解决方案整理
- 关于 IOS 开发中遇到的 读取 cell xib 文件时导致死机的问题。
- 关于iOS 7当中“编辑”与“新增”按钮的布局问题
- iOS开发 ----- 关于char *的赋值和字符串之间的复制问题以及sizeof strlen
- iOS中关于设置UIButton文字和图标对齐格式的问题
- 关于Unity发布iOS平台代码混淆问题
- 关于iOS审核由于ipv6环境下无法连接的问题
- 关于iOS拍照图片旋转90度问题