Here are 3 methods for making an actor’s image to have a transparent background.
All require the following import statement:
import java.awt.Color;
And turnTransparent3() requires:
import java.util.List;
/** * This method removes the color Color.WHITE * from the actor's image. */ private void turnTransparent() { GreenfootImage img = getImage(); Color transparent = new Color(0, 0, 0, 0); for(int x = 0; x < img.getWidth(); x++) { for(int y = 0; y < img.getHeight(); y++) { if(img.getColorAt(x, y).equals(Color.WHITE)) img.setColorAt(x, y, transparent); } } }
/** * This method removes the all whitish * colors from the actor's image. */ private void turnTransparent2() { int range = 10; //Should be in the range 0-255. GreenfootImage img = getImage(); Color transparent = new Color(0, 0, 0, 0); for(int x = 0; x < img.getWidth(); x++) { for(int y = 0; y < img.getHeight(); y++) { Color color = img.getColorAt(x, y); if(color.getRed() > 255 - range && color.getGreen() > 255 - range && color.getBlue() > 255 - range) img.setColorAt(x, y, transparent); } } }
/** * This method method finds the background * color and removes it from the actor's image. */ private void turnTransparent3() { GreenfootImage img = getImage(); Color transparent = new Color(0, 0, 0, 0); List<Color> colors = new ArrayList<Color>(); List<Integer> frequencys = new ArrayList<Integer>(); for(int x = 0; x < img.getWidth(); x++) { for(int y = 0; y < img.getHeight(); y++) { Color thisColor = img.getColorAt(x, y); int matchPos = colors.indexOf(thisColor); if(matchPos != -1) { frequencys.set(matchPos, frequencys.get(matchPos) + 1); } else { colors.add(thisColor); frequencys.add(1); } } } int maxFreq = 0, maxPos = 0; for(int i = 0; i < frequencys.size(); i++) { if(frequencys.get(i) > maxFreq) { maxFreq = frequencys.get(i); maxPos = i; } } Color bgColor = colors.get(maxPos); for(int x = 0; x < img.getWidth(); x++) for(int y = 0; y < img.getHeight(); y++) if(img.getColorAt(x, y).equals(bgColor)) img.setColorAt(x, y, transparent); }