如何计算两点之间的角度并将uiview旋转到这两点?

时间:2012-07-31 08:04:00

标签: ios xcode

我在一个UIView类的drawRect方法中制作一个箭头长度固定的箭头。 我必须计算ArrowView的中心和旋转角度,然后将其添加到我的视图中,使箭头显示从源到目标。

我使用的代码是

-(void)addArrowForChessMove:(CGPoint)source andDestination:(CGPoint)destination
{

    CGPoint centerOfArrow=CGPointMake((abs(source.x+destination.x)/2), (abs(source.y+destination.y)/2));

    DrawExperiment *drw=[[DrawExperiment alloc]initWithArrowHeight:70];
    drw.frame=CGRectMake(0,0, 25, 70);
    [drw setCenter:centerOfArrow];
    [drw setBackgroundColor:[UIColor clearColor]];
    [drw setTag:1002];

    float angleVal = atan2((destination.x - source.x) , (destination.y - source.y))*180/M_PI;
if ((destination.y -source.y) > 0) 
    {
        if((destination.x - source.x)<0)
        {
            angleVal= angleVal+M_PI_2;
        }
                 NSLog(@"%f====%f",(destination.y -source.y),(destination.x - source.x));


    }
    else if ((destination.y -source.y) < 0) 
    {
        if((destination.x - source.x)<0)
        {
            angleVal=angleVal+M_PI_2;
        }
        else{
            NSLog(@"%f====%f",(destination.y -source.y),(destination.x - source.x));
            angleVal= angleVal+M_PI;
        }

    }
    else if ((destination.x - source.x) < 0) 
    {
        if((destination.y -source.y)>=0)
        {
            angleVal= angleVal+M_PI;
        }
        else
        {
         NSLog(@"%f====%f",(destination.y -source.y),(destination.x - source.x));
        angleVal= M_PI;
        }
    }
    drw.transform=CGAffineTransformMakeRotation(angleVal);
    [self.view addSubview:drw];
    [self.view bringSubviewToFront:[self.view viewWithTag:1002]];




}`

` 该代码适用于水平轴或垂直轴,但当点的角度不是90的倍数时,那么结果的时间相反。

我失踪的是什么......谢谢

我添加了调整代码,因为箭头可以在任何方向上解决了许多问题,但仍存在45度和135度的问题......

注意: - 我欢迎马克作为一个健康的批评,但请写下你的降价评论的原因,以便我可以提高

0 个答案:

没有答案