Objective c 帮助正确计算atan2
我需要计算线之间的角度。我需要计算阿坦。所以我使用这样的代码Objective c 帮助正确计算atan2,objective-c,image-rotation,atan2,Objective C,Image Rotation,Atan2,我需要计算线之间的角度。我需要计算阿坦。所以我使用这样的代码 static inline CGFloat angleBetweenLinesInRadians2(CGPoint line1Start, CGPoint line1End) { CGFloat dx = 0, dy = 0; dx = line1End.x - line1Start.x; dy = line1End.y - line1Start.y; NSLog(@"\ndx = %f\ndy =
static inline CGFloat angleBetweenLinesInRadians2(CGPoint line1Start, CGPoint line1End)
{
CGFloat dx = 0, dy = 0;
dx = line1End.x - line1Start.x;
dy = line1End.y - line1Start.y;
NSLog(@"\ndx = %f\ndy = %f", dx, dy);
CGFloat rads = fabs(atan2(dy, dx));
return rads;
}
但是我不能超过180度((179度之后变成178、160、150度等等)
我需要360度旋转。我怎么做?怎么了
也许这有助于:
//Tells the receiver when one or more fingers associated with an event move within a view or window.
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSArray *Touches = [touches allObjects];
UITouch *first = [Touches objectAtIndex:0];
CGPoint b = [first previousLocationInView:[self imgView]]; //prewious position
CGPoint c = [first locationInView:[self imgView]]; //current position
CGFloat rad1 = angleBetweenLinesInRadians2(center, b); //first angel
CGFloat rad2 = angleBetweenLinesInRadians2(center, c); //second angel
CGFloat radAngle = fabs(rad2 - rad1); //angel between two lines
if (tempCount <= gradus)
{
[imgView setTransform: CGAffineTransformRotate([imgView transform], radAngle)];
tempCount += radAngle;
}
}
//当与事件关联的一个或多个手指在视图或窗口中移动时,通知接收器。
-(无效)触摸移动:(NSSet*)触摸事件:(UIEvent*)事件
{
NSArray*touchs=[touchs allObjects];
UITouch*first=[touchs objectAtIndex:0];
CGB点=[first previousLocationInView:[self imgView]];//前妻位置
CGPoint c=[first locationInView:[self imgView]];//当前位置
CGFloat rad1=直线之间的角度弧度2(中心,b);//第一个角度
CGFloat rad2=直线之间的角度弧度2(中心,c);//第二个角度
CGFloat radAngle=fabs(rad2-rad1);//两条线之间的角度
如果(tempCountatan2
以[-180180]为单位返回结果)(或-pi,以弧度为单位的pi)。要从0360获得结果,请使用:
float radians = atan2(dy, dx);
if (radians < 0) {
radians += M_PI*2.0f;
}
float弧度=atan2(dy,dx);
if(弧度<0){
弧度+=M_PI*2.0f;
}
需要注意的是,通常用[-pi,pi]表示旋转,因此您可以只使用atan2
的结果,而不必担心符号。删除fabs
调用,只需执行以下操作:
CGFloat rads = atan2(dy, dx);
在Swift中使用此函数。这确保从“fromPoint”到“toPoint”的角度在0到之间。您的问题是atan2的结果在-180到+180度之间。
如果希望其介于0和360之间,则移动结果以确保为正值,然后执行模运算。例如:
let angle = fmod(atan2(dx,dy) + .pi * 2, .pi * 2)
@yozhik:也许你应该解释一下什么不起作用。预期的结果是什么?你看到了什么?我有一个decart坐标系。我在这个坐标系上投影图片。这里有成像零点。当我在上180度拍摄并移动图片时——完全正确。当我尝试移动ander 180度时,例如190度——它显示我170度。我需要190度的地方。你看…@yozhik:试着移除fabs(rad2-rad1)中的其他fabs
还有。什么不起作用?我想你也用一个适当的常数替换了TWO\u PI
。我看不出有什么理由不能使你的角度正确。具体生成的值不正确?
let twoPi = 2 * Float(M_PI)
let radians = (atan2(-dy, -dx) + twoPi) % twoPi
let angle = radians * 360 / twoPi
let angle = fmod(atan2(dx,dy) + .pi * 2, .pi * 2)