开发者

Image rotation algorithm for a square pixel grid

开发者 https://www.devze.com 2023-03-31 01:53 出处:网络
I\'m currently working on my own littl开发者_如何学JAVAe online pixel editor. Now I\'m trying to add a rotation function.

I'm currently working on my own littl开发者_如何学JAVAe online pixel editor.

Now I'm trying to add a rotation function. But I can't quite figure out how to realize it.

Here is the basic query for my pixel grid:

for (var y = 0;y < pixelAmount;y++) {
    for (var x = 0;x < pixelAmount;x++) {
        var name = y + "x" + x;

        newY = ?? ;
        newX = ?? ;

        if ($(newY + "x" + newX).style.backgroundColor != "rgb(255, 255, 255)")
        { $(name).style.backgroundColor = $(newY + "x" + newX).style.backgroundColor; }
    }
}

How do I calculate newY and newX?


How do you rotate a two dimensional array?

from this^ post I got this method (in c#):

int a[4][4];
int n=4;
int tmp;
for (int i=0; i<n/2; i++){
        for (int j=i; j<n-i-1; j++){
                tmp=a[i][j];
                a[i][j]=a[j][n-i-1];
                a[j][n-i-1]=a[n-i-1][n-j-1];
                a[n-i-1][n-j-1]=a[n-j-1][i];
                a[n-j-1][i]=tmp;
        }
}   

or this one:

int[,] array = new int[4,4] {
    { 1,2,3,4 },
    { 5,6,7,8 },
    { 9,0,1,2 },
    { 3,4,5,6 }
};

int[,] rotated = RotateMatrix(array, 4);

static int[,] RotateMatrix(int[,] matrix, int n) {
    int[,] ret = new int[n, n];

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            ret[i, j] = matrix[n - j - 1, i];
        }
    }

    return ret;
}

the first method doesn't use a second array (/matrix) to save memory..


Take a look at this doc (Section 3: Rotating a bitmap with an angle of any value). It walks you through how to do the math and gives you some sample code (C++, but it should be good enough for what you need).


If very quick performance is not of huge importance (which is the case by default), you can consider rotating the picture clockwise by flipping it against the main diagonal and then horizontally. To rotate counterclockwise, flip horizontally, then against the main diagonal. The code is much simpler.

For diagonal flip you exchange the values of image[x,y] with image[y,x] in a loop like this

for( var x = 0; x < pixelAmount; ++x )
    for( var y = x + 1; y < pixelAmount; ++y )
        swap(image[x,y],image[y,x]);

For horizontal flip you do something like

    for( var y = 0; y < pixelAmount; ++y )
    {
        i = 0; j = pixelAmount - 1;
        while( i < j ) {
            swap( image[i,y], image[j,y] );
            ++i; --j;
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消