有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多维数组如何在java中对角反射图像

我有以下代码,以便以对角线方式反映图像:

public void mirrorDiagonal() {

      Pixel[][] pixels = this.getPixels2D();

      Pixel topRightPixel = null;
      Pixel bottomLeftPixel = null;
      int maxLength;
      if (pixels.length < pixels[0].length) { maxLength = pixels.length; }
      else {maxLength = pixels[0].length; }

      for (int row = 0; row < maxLength; row++)
      {
          for (int col = row; col < maxLength; col++)
          {
              topRightPixel = pixels[row][col];
              bottomLeftPixel = pixels[col][row];
              bottomLeftPixel.setColor(topRightPixel.getColor());
          }
      }
  }

然而,我在某个地方搞砸了,它从图像的右上角反射到左下角

我的问题是:我将如何以其他方式反映它?(更具体地说,从左上到右下)


共 (2) 个答案

  1. # 1 楼答案

    看起来你认为是右上角的像素实际上是左上角。请尝试以下方法:

    for (int row = 0; row < maxLength; row++) {
        for (int col = maxLength - row - 1; col >= 0; col ) {
            topRightPixel = pixels[row][col];
            bottomLeftPixel = pixels[col][row];
            bottomLeftPixel.setColor(topRightPixel.getColor());
        }
    }
    
  2. # 2 楼答案

    你为什么要改变颜色?你可以移动像素对象。此外,如果定义了3种基本转换,则可以通过以不同方式组合前3种来构造所有其他转换。 e、 g

    static void mirrorHor(Pixel[][] pixels) {
      for(int row = 0; row < pixels.length; row++) {
        for(int col = 0; col + col < pixels[row].length - 1; col++) {
          Pixel p = pixels[row][col];
          pixels[row][col] = pixels[row][pixels[row].length - col - 1];
          pixels[row][pixels[row].length - col - 1] = p;
        }
      }
    }
    
    static void mirrorVert(Pixel[][] pixels) {
      for(int row = 0; row + row < pixels.length - 1; row++) {
        Pixel[] r = pixels[row];
        pixels[row] = pixels[pixels.length - row - 1];
        pixels[pixels.length - row - 1] = r;
      }
    }
    
    static void mirrorTopRightBottomLeft(Pixel[][] pixels) {
      for(int row = 0; row < pixels.length - 1; row++) {
        for(int col = row + 1; col < pixels.length; col++) {
          Pixel p = pixels[row][col];
          pixels[row][col] = pixels[col][row];
          pixels[col][row] = p;
        }
      }
    }
    
    static void rotate180(Pixel[][] pixels) {
      mirrorHor(pixels);
      mirrorVert(pixels);
    }
    
    static void mirrorTopLeftBottomRight(Pixel[][] pixels) {
      mirrorTopRightBottomLeft(pixels);
      rotate180(pixels);
    }
    
    static void rotateLeft90(Pixel[][] pixels) {
      mirrorTopRightBottomLeft(pixels);
      mirrorVert(pixels);
    }
    
    static void rotateRight90(Pixel[][] pixels) {
      mirrorTopRightBottomLeft(pixels);
      mirrorHor(pixels);
    }