Chess effect on an image using Javafx

Asked

Viewed 113 times

0

I’m creating a function using Javafx so that it uses two images and the pixel size and returns a third image containing a checkered effect from the other two images.

Follow the code below,

public Image xadrez(Image img1, Image img2, int tamanho) {
int larg = (int) img1.getWidth();
int alt = (int) img1.getHeight();

WritableImage imgRes = new WritableImage(larg, alt);
PixelReader pr = img1.getPixelReader();
PixelReader pr2 = img2.getPixelReader();
PixelWriter pw = imgRes.getPixelWriter();

for (int x = 0; x < larg; x++) {
    for (int y = 0; y < alt; y++) {
        if ( x % 2 == y % 2)
            pw.setArgb(x, y, pr.getArgb(x, y));
        else
            pw.setArgb(x, y, pr2.getArgb(x, y));
    }
} 
return imgRes;

}

The whole problem is that I’m not getting a way to put the size of pixels, the code above returns an image with the checkered effect but using only 1 pixel of each image at a time. What I would like to do is use the size variable to get a larger group of pixels, such as 10 pixels at a time.

1 answer

1


A way of doing, assuming that "size" fits the two dimensions of each square of chess, is like this:

for (int x = 0; x < larg; x++) {
    for (int y = 0; y < alt; y++) {
        if ( (((x/tamanho) % 2 == 0) && ((y/tamanho) % 2 == 0)) || 
             (((x/tamanho) % 2 == 1) && ((y/tamanho) % 2 == 1)) )
            pw.setArgb(x, y, pr.getArgb(x, y));
        else
            pw.setArgb(x, y, pr2.getArgb(x, y));
    }
} 

===========

(edited) Another way, less clear, but more elegant:

    for (int x = 0; x < larg; x++) {
        for (int y = 0; y < alt; y++) {
            if ( ((x/tamanho) % 2 == (y/tamanho) % 2 ) ) 
                pw.setArgb(x, y, pr.getArgb(x, y));
            else
                pw.setArgb(x, y, pr2.getArgb(x, y));
        }
    } 
  • It worked!! Thank you so much for your help!

  • Interesting this other way, I’ll save you here too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.