Java:如何旋转非平方2D数组

Java:如何旋转非平方2D数组,java,arrays,2d,rgb,dimensional,Java,Arrays,2d,Rgb,Dimensional,我将其作为颜色数组: public RGBImage(int width, int height, RGBColor background) { pixel = new RGBColor[width][height]; this.w = width; this.h = height; this.b = background; for(x = 0; x < width; x++){ for(y = 0; y

我将其作为颜色数组:

public RGBImage(int width, int height, RGBColor background) {
      pixel =  new RGBColor[width][height];
      this.w = width;
      this.h = height;
      this.b = background;

      for(x = 0; x < width; x++){
          for(y = 0; y < height; y++){
              pixel[x][y] = b;
          }
      }
公共RGB图像(整幅宽度、整幅高度、RGB彩色背景){
像素=新RGB颜色[宽度][高度];
这个。w=宽度;
h=高度;
b=背景;
对于(x=0;x
我想旋转它,对吧,由于@Oblivion Creations,代码在方阵方面已经做得很好了,但是在使用非方阵时,我得到了超出边界的错误

   public void rotateRight() {
      RGBColor[][] mirror = new RGBColor[h][w];
              for(int i = 0 ; i < h; i++){
                  for(int j = 0 ; j < w; j++){
                      mirror[i][j] = pixel[j][w-i-1];
                  }
              }
            pixel = mirror;
  }
public void rotateRight(){
RGBColor[][]镜像=新RGBColor[h][w];
对于(int i=0;i
我认为问题在于
镜像=像素;
共享相同的引用…因此它在旋转时会改变自身,导致它做一些奇怪和奇妙的事情

我的建议是从像素复制到镜像,然后在for循环后将镜像分配给像素,如下所示:

public void rotateLeft() {
    RGBColor[][] mirror = new RGBColor[w][h];
    if(w == h){
        for(int i = 0 ; i < h; i++){
            for(int j = 0 ; j < h; j++){
                mirror[i][j] = pixel[h-j-1][i];
            }
        }
        pixel = mirror;
    }
}
public void rotateLeft(){
RGBColor[][]镜像=新RGBColor[w][h];
如果(w==h){
对于(int i=0;i
编辑:

对于新的RotateRight,您使用的是宽度变量,而不是未旋转像素阵列上的高度。请尝试以下操作:

public void rotateRight() {
   RGBColor[][] mirror = new RGBColor[h][w];
           for(int i = 0 ; i < h; i++){
               for(int j = 0 ; j < w; j++){
                   mirror[i][j] = pixel[j][h-i-1];
               }
           }
         pixel = mirror;
}
public void rotateRight(){
RGBColor[][]镜像=新RGBColor[h][w];
对于(int i=0;i
问题是
mirror=pixel
分配
mirror
引用与
pixel
相同的数组。它不会复制数组。因此在循环中,
pixel[i][j]=mirror[h-j-1][i]
将一个像素从阵列的一个单元复制到同一阵列的另一个单元

谢谢你,它工作得很好!关于将其升级到非方形矩阵的任何提示?不用担心!事实上,是的,我在回答后正在考虑……将镜像的创建更改为
RGBColor[]镜像=新RGBColor[h][w]
(反转宽度和高度),删除if检查,应该可以继续。是的,我这样做了,现在只需要解决循环中的一些问题,目前这样做:但是有越界,这是有意义的,只是还没有找到办法及时停止。thx再次。
mirror[I][j]=pixel[j][w-I-1]
应该是
镜像[i][j]=pixel[j][h-i-1];
是的,现在旋转很好!最后一个问题是我的getRGB算法,当h!=w,无法真正找到原因。再次感谢所有帮助。