一个图形或者控件旋转时 判断方向逆时针还是顺时针

 

在图形操作中有时候会遇到对一个控件用鼠标进行旋转,比如 左键按住控件旋转。但是在旋转的时候如何判断旋转的方向呢?这儿提供一个方法,但是该方法有缺陷,在旋转到垂直的时候有问题。

 

/// <summary>
        /// 判断旋转的方向 顺时针或者逆时针
        /// </summary>
        /// <param name="center">控件旋转的中心点,该方法中的点都是相对于控件本身的坐标系</param>
        /// <param name="startPoint">鼠标起始位置</param>
        /// <param name="currentPoint">当前鼠标所在位置</param>
        /// <returns>顺时针方向 1, 逆时针方向 -1</returns>
        private int GetRotateDirection(Point center, Point startPoint, Point currentPoint)
        {
            int direct = 1;
            if (startPoint.X != center.X && currentPoint.X != center.X)
            {
                double k = (startPoint.Y - center.Y) / (startPoint.X - center.X);
                double k2 = (currentPoint.Y - center.Y) / (currentPoint.X - center.X);
                direct = k > k2 ? -1 : 1;
            }
            return direct;
        }

 

经过研究,找到了第二种方法,即用向量判断的叉乘来计算鼠标移动方向的方法,直接贴出示例代码:

    
        ///
        /// 判断旋转的方向 顺时针或者逆时针
        /// </summary>
        /// <param name="center">控件旋转的中心点,在选择坐标系的时候最好选择不动的容器(比如Grid,Canvas)作为坐标系</param>
        /// <param name="startPoint">鼠标起始位置</param>
        /// <param name="currentPoint">当前鼠标所在位置</param>
        /// <returns>顺时针方向 1, 逆时针方向 -1</returns>

        public static int CalculatorDirect(PointT A, PointT B, PointT C)
        {
            PointT AB = new PointT() { X = B.X - A.X, Y = B.Y - A.Y, Z = B.Z - A.Z };
            PointT AC = new PointT() { X = C.X - A.X, Y = C.Y - A.Y, Z = C.Z - A.Z };
            PointT direct = new PointT() { X = 0, Y = 0 };
            direct.Z = AB.X * AC.Y - AB.Y * AC.X;
            return direct.Z > 0 ? 1 : -1;
        }


public struct PointT
    {
        public PointT(double x, double y, double z)
        {
            X = x;
            Y = y;
            Z = z;
        }
        public double X;
        public double Y;
        public double Z;
    }

 

 PointT 结构表示XYZ坐标系中的点,也用来表示三维向量。

下面的方法是计算A, B, C 三个点,AB和AC的夹角的方法(用平面向量的方法计算):

   public static double CalculatorAngle(Point A, Point B, Point C)
        {
            Point AB = new Point() { X = B.X - A.X, Y = B.Y - A.Y };
            Point AC = new Point() { X = C.X - A.X, Y = C.Y - A.Y };

            double arctCos = (AB.X * AC.X + AB.Y * AC.Y) / (Math.Sqrt(AB.X * AB.X + AB.Y * AB.Y) * Math.Sqrt(AC.X * AC.X + AC.Y * AC.Y));
            double angle = Math.Acos(arctCos);
            return angle;
        }
posted @ 2013-09-11 17:08  仰望星辰  阅读(1270)  评论(0编辑  收藏  举报