问题
How would I tint the icon that is passed through here to be a different color? Say I wanted to take a white image and make it a bit darker. I have looked into BufferedImages and such but I can't seem to find anything that will fit into the setup that I am using. I should also note that I am drawing the images onto a JLabel if that makes a difference.
Here is the source that I am using so that you can get an idea as to what I am working with.
public class Icon extends ImageIcon{
private int scale = 1;
private boolean mirror = false;
public Icon(URL url) throws IOException{
super(ImageIO.read(url));
}
public void setScale(int scale){
this.scale = scale;
}
@Override
public synchronized void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2 = (Graphics2D)g.create();
int height = 0, width = this.getIconWidth(), x1 = 1;
if(mirror || scale != 1){
height = -this.getIconHeight();
}
if(mirror){
x1 = -1;
}else{
width = 0;
}
g2.translate(width * scale, height);
g2.scale(x1 * scale, 1 * scale);
super.paintIcon(c, g2, x, y);
}
public boolean isMirror() {
return mirror;
}
public void setMirror(boolean mirror) {
this.mirror = mirror;
}
}
回答1:
you need to create a new BufferedImage to make the transform into:
public BufferedImage colorImage(BufferedImage loadImg, int red, int green, int blue) {
BufferedImage img = new BufferedImage(loadImg.getWidth(), loadImg.getHeight(),
BufferedImage.TRANSLUCENT);
Graphics2D graphics = img.createGraphics();
Color newColor = new Color(red, green, blue, 0 /* alpha needs to be zero */);
graphics.setXORMode(newColor);
graphics.drawImage(loadImg, null, 0, 0);
graphics.dispose();
return img;
}
来源:https://stackoverflow.com/questions/30444232/how-to-tint-an-imageicon