Rotate a point around another point

后端 未结 2 1310
天涯浪人
天涯浪人 2020-12-01 08:09

I have a task to draw a specific graphic. As part of this task I need to rotate some dot\'s on 45 degrees.

I\'ve spent already 2 days trying to calculate a formula,

2条回答
  •  醉酒成梦
    2020-12-01 08:36

    The problem is int center = radius which you are setting int radius = 576. This doesn't make sense as surely you are rotating about a point that should have an x and y location.

    Given you are rotating around the origin the center x and y should both be 0 not 576.

    So, given that, try this.

    /// 
    /// Rotates one point around another
    /// 
    /// The point to rotate.
    /// The center point of rotation.
    /// The rotation angle in degrees.
    /// Rotated point
    static Point RotatePoint(Point pointToRotate, Point centerPoint, double angleInDegrees)
    {
        double angleInRadians = angleInDegrees * (Math.PI / 180);
        double cosTheta = Math.Cos(angleInRadians);
        double sinTheta = Math.Sin(angleInRadians);
        return new Point
        {
            X =
                (int)
                (cosTheta * (pointToRotate.X - centerPoint.X) -
                sinTheta * (pointToRotate.Y - centerPoint.Y) + centerPoint.X),
            Y =
                (int)
                (sinTheta * (pointToRotate.X - centerPoint.X) +
                cosTheta * (pointToRotate.Y - centerPoint.Y) + centerPoint.Y)
        };
    }
    

    Use like so.

    Point center = new Point(0, 0); 
    Point newPoint = RotatePoint(blueA, center, 45);
    

    Obviously if the center point is always 0,0 then you can simplify the function accordingly, or else make the center point optional via a default parameter, or by overloading the method. You would also probably want to encapsulate some of the reusable math into other static methods too.

    e.g.

    /// 
    /// Converts an angle in decimal degress to radians.
    /// 
    /// The angle in degrees to convert.
    /// Angle in radians
    static double DegreesToRadians(double angleInDegrees)
    {
       return angleInDegrees * (Math.PI / 180);
    }
    
    /// 
    /// Rotates a point around the origin
    /// 
    /// The point to rotate.
    /// The rotation angle in degrees.
    /// Rotated point
    static Point RotatePoint(Point pointToRotate, double angleInDegrees)
    {
       return RotatePoint(pointToRotate, new Point(0, 0), angleInDegrees);
    }
    

    Use like so.

    Point newPoint = RotatePoint(blueA, 45);
    

    Finally, if you are using the GDI you can also simply do a RotateTransform. See: http://msdn.microsoft.com/en-us/library/a0z3f662.aspx

    Graphics g = this.CreateGraphics();
    g.TranslateTransform(blueA);
    g.RotateTransform(45);
    

提交回复
热议问题