Home > Back-end >  Rotate an image with trigonometry
Rotate an image with trigonometry

Time:12-13

i would like to rotate an image like the next gif: rotation that i want

but i'm getting this result:

wrong rotation

public int[] rotateByAngle(int posx, int posz, double angle){
    double radians = Math.toRadians(angle);
    double cos = Math.cos(radians);
    double sin = Math.sin(radians);



    int rotate_x  = (int) Math.floor((posx * cos - posz * sin)) ;
    int rotate_z  = (int) Math.floor((posx * sin    posz * cos)) ;


    return new int[] {rotate_x ,rotate_z };
}
public void drawImage(MapCanvas canvas,int x, int y, BufferedImage image,double angle) {
    byte[] bytes = MapPalette.imageToBytes(image);

    for(int x2 = 0; x2 < image.getWidth();   x2) {
        for(int y2 = 0; y2 < image.getHeight();   y2) {
            byte c =  bytes[y2 * image.getWidth()   x2];
            if(c == 0) continue;
            int [] sol = rotateByAngle(x2,y2,angle);
            canvas.setPixel(x   sol[0], y   sol[1],c);
        }
    }

}
drawImage(canvas,64,64, img.getBufferedImage(),angle);

i dont want to use => AffineTransform at = new AffineTransform(); i would like to use cos and sen

CodePudding user response:

Centre of the rotation is like on point (0,0), try to set it in a place where it is at the beginning

CodePudding user response:

public void drawImage(MapCanvas canvas,int x, int y, BufferedImage image,double angle) {
    byte[] bytes = MapPalette.imageToBytes(image);

    int real_x = image.getWidth()/2;
    int real_y = image.getHeight()/2;

    for(int x2 = 0; x2 < image.getWidth();   x2) {
        for(int y2 = 0; y2 < image.getHeight();   y2) {

            byte c =  bytes[y2 * image.getWidth()   x2];
            if(c == 0) continue;
            int [] sol = rotateByAngle(x2-real_x,y2-real_y,angle);
            canvas.setPixel(x   sol[0], y   sol[1],c);

        }
    }

}
  • Related