gpt4 book ai didi

ios - 测量在 iPhone 屏幕上绘制的线的距离

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:17:51 25 4
gpt4 key购买 nike

我正在尝试创建一个应用程序,允许用户在屏幕上画一条线并测量所画线的距离。我已经能够成功地画出线,但我不知道如何测量它。这条线也不必完全笔直。它基本上是一个波浪线。如果有人可以给我指出正确的方向或帮助指导我,那将是非常棒的。我正在使用 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];
}

最佳答案

首先添加一个累积路径长度的属性。

@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。

关于ios - 测量在 iPhone 屏幕上绘制的线的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24788764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com