我正在使用swing在java中设计Pac Man。我使用以下语句在屏幕上绘制了PNG图像。
wall = new ImageIcon(GamePanel.class.getResource("wall.png")).getImage();
g2d.drawImage(wall, x, y, this);
我遇到的问题是它似乎呈现了实际文件的非常低的颜色深度再现。看起来它确实保持透明度(灰色背景是Panel bg颜色),但它会失去颜色深度。
实际图片如下所示:运行时,它看起来像这样:
有没有人有解决方案?谢谢!
答案 0 :(得分:4)
第二张图片中似乎有些错误。在黑色BG上看到它看起来非常不同 - 没有'光环'。
import java.awt.*;
import java.net.URL;
import javax.swing.*;
public class TestYellowDotImage {
public static JLabel getColoredLabel(Icon icon, Color color) {
JLabel label = new JLabel(icon);
label.setBackground(color);
label.setOpaque(true);
return label;
}
public static void main(String[] args) throws Exception {
URL url = new URL("http://i.stack.imgur.com/1EZVZ.png");
final Icon icon = new ImageIcon(url);
Runnable r = new Runnable() {
@Override
public void run() {
JPanel gui = new JPanel(new GridLayout(0, 4));
gui.add(new JLabel(icon));
gui.add(getColoredLabel(icon, Color.BLACK));
gui.add(getColoredLabel(icon, Color.WHITE));
gui.add(getColoredLabel(icon, Color.RED));
JOptionPane.showMessageDialog(null, gui);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
答案 1 :(得分:3)
在g2d
上尝试此设置: -
Map<RenderingHints.Key, Object> map = new HashMap<RenderingHints.Key, Object>();
map.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
map.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
map.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
RenderingHints renderHints = new RenderingHints(map);
g2d.setRenderingHints(renderHints);
答案 2 :(得分:3)
使用Grid
,您可以将鼠标悬停在像素上,以查看Alpha组件在图标边缘的滚动方式。
public Grid(String name) {
this.setBackground(new Color(0xFFFFFFC0));
Icon icon = null;
try {
icon = new ImageIcon(new URL("http://i.stack.imgur.com/1EZVZ.png"));
} catch (MalformedURLException e) {
e.printStackTrace(System.err);
}
...
}
此IconTest
显示图标如何使用不同的alpha和默认AlphaComposite.SRC_OVER
规则呈现。
/*** @see https://stackoverflow.com/a/14432025/230513 */
public class IconTest {
private static final int N = 8;
private static final Random r = new Random();
public static void main(String[] args) throws MalformedURLException {
final URL url = new URL("http://i.stack.imgur.com/1EZVZ.png");
final Icon icon = new ImageIcon(url);
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new JFrame("IconTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel(new GridLayout(N, N));
for (int i = 0; i < N * N; i++) {
final JLabel label = new JLabel(icon);
label.setOpaque(true);
label.setBackground(new Color(0, 0, 255, i));
p.add(label);
}
f.add(p);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
}
答案 3 :(得分:2)
解决。在paint()方法中使用了repaint()。删除它,它的工作原理。
感谢您的帮助。