如何使用Java 2D Arrays水平镜像图像?

时间:2016-04-05 20:27:57

标签: java arrays image for-loop 2d

问候男孩和女孩我偶然发现了一个我似乎无法弄清楚的问题,而且类似的帖子结构与我使用的不同。因此,我非常感谢一些指导。我们来看看我的水平镜像方法:

  public void  mirrorHorizontal(){
  Pixel[][] pixels = this.getPixels2D();     
  Pixel topPixel = null;     
  Pixel bottomPixel = null;     
  int width = pixels[0].length;     
  for (int row = 0; row < pixels.length / 2; row++){       
      for (int col = 0; col < width; col++){         
          bottomPixel = pixels[row][col];        
          topPixel = pixels[row][col];         
          bottomPixel.setColor(topPixel.getColor());       
      }     
  } }

让我们确定提供此代码以供使用和修改,以便我尽力解释。

在这个for循环中,我所做的是通过将pixels.length乘以2来将行切成两半,这样我就可以在顶部获得顶部图片,在底部获得一个。

for (int row = 0; row < pixels.length / 2; row++){  

所以我相信这是我的问题:

bottomPixel = pixels[row][col];        
topPixel = pixels[row][col];

我不知道将什么放在bottomPixel [row] [col]

我相信它必须呈现这样的东西:

  1. 1 2 3 4
  2. 5 6 7 8
  3. 5 6 7 8
  4. 1 2 3 4
  5. 但是我不确定如何修改它来实现这一点。

    这使用两个修改过的for循环&amp;不同的值,以实现类似的效果,以通过AngryDuck翻转多维数组java。

1 个答案:

答案 0 :(得分:0)

因此,在您的示例中,bottomPixeltopPixel完全相同。

如果我理解你的问题,这将解决你的问题:

for (int row = 0; row < pixels.length / 2; row++){       
  for (int col = 0; col < pixels[0].length; col++){                 
      topPixel = pixels[row][col];  
      bottomPixel = pixels[(pixels.length - 1) - i][col];       
      bottomPixel.setColor(topPixel.getColor());       
  }     
} 

我更改了bottomPixel的行坐标,因此它将从底部获取镜像坐标。但这仅在您的图片具有pixels.length / 2行时才有效。