我正在尝试创建一个应用程序,允许用户在屏幕上绘制一条线,并测量绘制线的距离。我已经能够成功画线,但我不知道如何测量它。该线也不一定非常直。它基本上是一个波浪形。如果有人可以请我指出正确的方向或帮助指导我,这将是非常棒的。我正在使用Xcode 5.1.1和objective-c。我今年夏天才开始涉足这门语言。
编辑:我希望以英寸或厘米为单位测量距离。我希望测量是整条线,遵循线的曲线。距离不是位移。-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
mouseSwipe = YES; //swipe declared in header
UITouch *touch = [touches anyObject];
currentPoint = [touch locationInView:self.view]; //tracking finger movement on screen
UIGraphicsBeginImageContext(CGSizeMake(320, 568)); // 568 iphone 5, 480 is iphone 4 (320,525)
[drawImage.image drawInRect:CGRectMake(0, 0, 320, 568)]; // 0,0 centered in corner
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound); //round line end
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0); // width of line
CGContextSetStrokeColorWithColor(UIGraphicsGetCurrentContext(), [[UIColor redColor] CGColor]); //sets color to red (change red to any color for that color)
//CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0,1,0,1); //green color
CGContextBeginPath(UIGraphicsGetCurrentContext()); //start of when drawn path
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
[drawImage setFrame:CGRectMake(0, 0, 320, 568)]; //(320, 568)
drawImage.image = UIGraphicsGetImageFromCurrentImageContext(); //importnant
UIGraphicsEndImageContext(); //finished drawing for time period
lastPoint = currentPoint;
[self.view addSubview:drawImage]; //adds to page
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject]; //touch fires of touch
location = [touch locationInView:touch.view];
lastClick = [NSDate date];
lastPoint = [touch locationInView:self.view]; //stops connecting to previous line
lastPoint.y -= 0;
[super touchesEnded:touches withEvent: event];
}
答案 0 :(得分:1)
首先添加一个累积路径长度的属性。
@property(nonatomic, assign) CGFloat pathLength;
当用户开始绘制路径时,将其初始化为0.0
。也许在touchesBegan中执行此操作,或者在代码中的其他地方执行此操作,您会发现自己已经开始绘制。添加一个计算点之间的笛卡尔距离的方法:
- (CGFloat)distanceFrom:(CGPoint)p1 to:(CGPoint)p2 {
CGFloat x = (p2.x - p1.x);
CGFloat y = (p2.y - p1.y);
return sqrt(x*x + y*y);
}
当您触摸移动时,您已经处理了当前和最后的触摸位置。你现在要做的就是累计连续点之间的距离:
// in touches moved, after you have lastPoint and currentPoint
self.pathLength += [self distanceFrom:currentPoint to:lastPoint];
这里和其他地方有很多参考将这些点转换为英寸或厘米。据我所知,所有人都无法在运行时从SDK获得设备解析。如果您愿意在代码中添加(危险)常量,可以get PPI here,并将其除以上面计算的pathLength。