Question

I'm stitching a bitmap from a layout array, that puts the a larger bitmap together as a guide. Using multiple bitmaps into one bitmap. What I rotate the whole bitmap, my solution is to restitch it but have the array account for this rotation. The making of the bitmap is determined by the order of the array. The stitching assumes that the array starts from zero and that is the first index or the left top most corner and then goes to the right to the end and goes to beginning of the next row. I would like to have a 90, 180, 270, and 360 functions to call on. I'm thinking 360 is easy I iterate backwards. I'm using 11 by 11 which is constant.

For example

0, 1, 3, 4
5, 6, 7, 8,
9, 10, 11, 12
13, 14, 15, 16

when I rotate 90

4, 8, 12, 16
3, 7, 11, 15
1, 6, 10, 14
0, 5, 9,  13
Was it helpful?

Solution

Try this. This may have performance impact but its a simple solution.

import java.util.Arrays;

public class RotateMatrix {

    public static void main(String[] args) {
        int original[][] = { { 0, 1, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 },
                { 13, 14, 15, 16 } };

        printArray(original);
        System.out.println("After 90 Degree");
        printArray(rotate(original, 90));
        System.out.println("After 180 Degree");
        printArray(rotate(original, 180));
        System.out.println("After 270 Degree");
        printArray(rotate(original, 270));
        System.out.println("After 360 Degree");
        printArray(rotate(original, 360));
    }

    private static int[][] rotate(int[][] original, int angle) {

        int[][] output = original;
        int times = 4 - angle/90;

        for(int i=0; i<times; i++){
            output = rotate(output);
        }

        return output;
    }

    private static int[][] rotate(int[][] original) {

        int n = original.length;
        int m = original[0].length;
        int[][] output = new int[m][n];

        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                output[j][n - 1 - i] = original[i][j];
        return output;
    }

    private static void printArray(int[][] array) {
        for (int i = 0; i < array.length; i++) {
            System.out.println(Arrays.toString(array[i]));
        }
    }

}

This rotates the array anti-clockwise direction just as in your example. However if you want to change this to clockwise just change int times = 4 - angle/90; to int times = angle/90; in rotate(int[][] original, int angle) method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top