Rotates a point around the origin (0, 0) by a specified angle - Android Graphics

Android examples for Graphics:Path Point

Description

Rotates a point around the origin (0, 0) by a specified angle

Demo Code


//package com.java2s;
import android.graphics.Matrix;
import android.graphics.PointF;

public class Main {
    private static Matrix matrix = new Matrix();

    /**//  w  ww .  ja va 2s  .  com
     * Rotates a point around the origin (0, 0) by a specified angle
     * @param p The point to be rotated
     * @param angleRadians The rotation angle (measured in radians)
     * @return The rotated point
     */
    public static PointF rotate(PointF p, double angleRadians) {
        double angleCosine = Math.cos(angleRadians);
        double angleSine = Math.sin(angleRadians);
        return rotate(p, angleCosine, angleSine);
    }

    /**
     * Rotates a point around the origin (0, 0) by a specified angle
     * @param p The point to be rotated
     * @param angleCosine The cosine of the rotation angle
     * @param angleSine The sine of the rotation angle
     * @return The rotated point
     */
    public static PointF rotate(PointF p, double angleCosine,
            double angleSine) {
        double newX = p.x * angleCosine - p.y * angleSine;
        double newY = p.y * angleCosine + p.x * angleSine;
        return new PointF((float) newX, (float) newY);
    }

    /**
     * Rotate a point around another point by a specified angle. This is great for figuring out the
     * coordinates of an attachment part when the ship is rotated.
     * eg: Calculate the attachment point offset. Pass that in as pointToRotate, pass the main body point in the world
     * as rotateAroundThisPoint, and the number of degrees to rotate. The return value is where the attachement
     * point should be drawn in world space (you will still need to convert from world to view before drawing)
     * @param pointToRotate The point that will be rotated
     * @param rotateAroundThisPoint rotate "pointToRotate" around this point. (As if rotateAroundThisPoint was the center)
     * @param degreesToRotate The number of degrees to rotate around.
     * @return
     */
    public static PointF rotate(PointF pointToRotate,
            PointF rotateAroundThisPoint, double degreesToRotate) {
        matrix.reset();
        matrix.preTranslate(-rotateAroundThisPoint.x,
                -rotateAroundThisPoint.y);
        matrix.preRotate((float) degreesToRotate);
        matrix.postTranslate(rotateAroundThisPoint.x,
                rotateAroundThisPoint.y);

        float[] arr = new float[] { (pointToRotate.x), (pointToRotate.y) };
        float[] dest = new float[2];
        matrix.mapPoints(dest, arr);
        return new PointF((int) dest[0], (int) dest[1]);
    }
}

Related Tutorials