This site requires JavaScript, please enable it in your browser!
Greenfoot back
K_wow
K_wow wrote ...

2013/7/20

How to check the colour of a pixel in an image, then change it?

K_wow K_wow

2013/7/20

#
I'm experimenting with a game that allows you to change the colour of the shirt of your player. I'm using this code:
    
    public void setColour(Color colourToOverwrite, Color colourToUse)
    {
        GreenfootImage currentImage = getImage();
        for (int currentPixel = 0; currentPixel < currentImage.getHeight(); currentPixel++)
        {
            fillRow(colourToOverwrite, colourToUse, currentPixel, currentImage);
        }
    }
    
    public void fillRow(Color oldColour, Color newColour, int y, GreenfootImage image)
    {
        for (int currentPixel = 0; currentPixel < image.getWidth(); currentPixel++)
        {
            if (image.getColorAt(currentPixel, y) == oldColour)
            {
                image.setColorAt(currentPixel, y, newColour);
            }
        }
    }
However, the shirt colours do not change. Does anyone know what I'm doing wrong?
davmac davmac

2013/7/20

#
Line 14 uses reference equality (the == operator) to compare the oldColour object with the colour object returned by getColorAt(). Even if the two objects specify the same colour, there's no guarantee that they'll be the same object. You should use .equals(...) for this check rather than the == operator. if (image.getColorAt(currentPixel, y).equals(oldColour)) ...
K_wow K_wow

2013/7/20

#
davmac wrote...
Line 14 uses reference equality (the == operator) to compare the oldColour object with the colour object returned by getColorAt(). Even if the two objects specify the same colour, there's no guarantee that they'll be the same object. You should use .equals(...) for this check rather than the == operator. if (image.getColorAt(currentPixel, y).equals(oldColour)) ...
Thankyou, it works perfectly!
You need to login to post a reply.