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

2024/7/19

Removing / Erasing pixels from a Transparent background

MrBradley MrBradley

2024/7/19

#
It seems that I need to use GreenfootImage#setColorAt(...) with a transparent Color(0,0,0,0) in order to remove / erase pixels, instead of GreenfootImage#drawRect(...) after setting the image color to transparent. This surprised me and seems counter intuitive. Can someone offer an explanation, please? Thanks in advance. Details I have a simple actor that is a transparent window that is placed over other actor locations. It can have a border drawn on it to draw focus to that location. Then the border can be reset or cleared.
    public void drawBorder( Color c ) {
        GreenfootImage img = getImage();
        int width = img.getWidth();
        int height = img.getHeight();
        img.setColor( c );
        for( int i=0; i<BORDER_WIDTH; i++ ) {
            img.drawRect(i, i, width-(2*i+1), height-(2*i+1) );
        }
    }
and then
    public void clearBorder() {
        drawBorder( new Color( 0, 0, 0, 0 ) );
    }
but this doesn't appear to work. Instead I had to use this approach:
    public void erase() {
        GreenfootImage img = getImage();
        Color color = new Color( 0,0,0,0 );   
        img.setColor( color );
        
        for( int r=0; r<img.getWidth(); r++ )
            for(int c=0; c<img.getHeight(); c++ ) 
                if( r < BORDER_WIDTH || 
                    r > img.getHeight() - BORDER_WIDTH - 1 ||
                    c < BORDER_WIDTH ||
                    c > img.getWidth() - BORDER_WIDTH - 1 )
                        img.setColorAt(r, c, color); 

    }
I would have expected the drawRect method to eventually call the setColor method....? Thanks.
danpost danpost

2024/7/20

#
MrBradley wrote...
It seems that I need to use GreenfootImage#setColorAt(...) with a transparent Color(0,0,0,0) in order to remove / erase pixels, instead of GreenfootImage#drawRect(...) after setting the image color to transparent. This surprised me and seems counter intuitive. Can someone offer an explanation, please? Thanks in advance. << Details Omitted >>
Drawing is like painting. Using clear paint, you cannot remove or hide any color that might already be there. That is, opaque colors remain as is. I would suggest that you use the clear method to erase the image:
getImage().clear();
(no need for an additional erase method) Or, alternate between two separate images, which would preclude the need for manipulating images at all (once created and, if needed, draw on). If you have other stuff drawn on the image that needs to remain when the border is removed, then maybe you could draw the image on a smaller image (removing the border), then draw the smaller image at the proper place on a new image of proper size.
You need to login to post a reply.