5.2k views
2 votes
Write the method mirrorVerticalRightToLeft that mirrors a picture around a mirror placed vertically from right to left.

User Grant Park
by
7.1k points

1 Answer

3 votes

Answer:

Here is the method mirrorVerticalRightToLeft

public void mirrorVerticalRightToLeft() { //method definition

Pixel[][] pixels = this.getPixels2D(); //uses getPixels2D() method which returns a two-dimensional array of Pixel object and stores this in pixels

Pixel leftPixel = null; //Pixel object leftPixel set to null

Pixel rightPixel = null; //Pixel object rightPixel set to null

int width = pixels[0].length; // returns the length of 0-th element of pixels and assigns it to width

for (int row = 0; row < pixels.length; row++) { //iterates through the rows of pixels array

for (int col = 0; col < width / 2; col++) { //iterates through the columns of pixels array

leftPixel = pixels[row][col]; //sets leftPixel to a certain point of row and column of pixel array

rightPixel = pixels[row][width - 1 - col]; //sets rightPixel to a certain point of row and column of pixel array

leftPixel.setColor(rightPixel.getColor()); } } } //uses object leftPixel to call setColor() method to set color of leftPixel to specified color and rightPixel is used to call getColor method to get the current color

Step-by-step explanation:

The method mirrorVerticalRightToLeft is used to mirror a picture around a mirror placed vertically from right to left. It uses two loops, the outer loop iterates through each row and inner loop iterates through columns as long as the col variable stays less than width / 2 whereas width is set to pixels[0].length which compute the length of 0-th pixel. At each iteration we have the two position instance variables i.e. leftPixel and rightPixel such that leftPixel is set to pixels[row][col] and rightPixel is set to pixels[row][width - 1 - col]; For example if row = 0 and col = 0 then

leftPixel = pixels[0][0] which means it is positioned at 0th row and 0th column of 2D pixels array so it is positioned at the 1st pixel/element. It works this way at each iteration.

rightPixel = pixels[row][width - 1 - col]; for same example becomes:

rightPixel = pixels[0][width - 1 - 0];

So whaterbe is the value of width, the rightPixel is positioned at 0th row and width-1th column. Now after each of leftPixel and rightPixel is placed to the desired pixel of pixels array then next the statement: leftPixel.setColor(rightPixel.getColor()); executes in which leftPixels calls setColor which sets the color to the specified color and rightPixel calls getColor method to get the current color. Suppose getColor returns the color blue so this color is set to leftPixel and this is how the picture is mirrored.

User Douglas Daseeco
by
7.0k points