我用 Java 编写了我的第一个游戏。所以我有 Board 类扩展了 JPanel,并且在这个类中我有 PaintComponent 方法。卡片图像是 BufferedImages。
现在...我刚刚完成了计算可能的玩家移动的方法。为了澄清一下,我有敌人的卡牌字段,每次当敌人的卡牌字段在玩家移动范围内时,我想向敌人的卡牌字段图像添加一些图层。
我在paintComponent方法中的代码是这样的:
if(!field.isWithinMove()){
//draw normal state card
g.drawImage(field.getLoadedCard().getCardImage(),
field.getX(), field.getY(), Card.cardWidth, Card.cardHeight, null);
}
else{
//there should be a card picture with layer of color
}
我的目标是:
正常:
突出显示:
我将非常感谢您的帮助:)
干杯!
最佳答案
您可以使用 AlphaComposite
来更改图形渲染的方式,例如...
import java.awt.AlphaComposite;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private BufferedImage img;
public TestPane() {
try {
img = ImageIO.read(source of your image here);
} catch (IOException ex) {
Logger.getLogger(JavaApplication393.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(189 * 2, 270);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
// Normal
g2d.drawImage(img, 0, 0, this);
// Highlighted
g2d.drawImage(img, img.getWidth(), 0, this);
g2d.setComposite(AlphaComposite.SrcOver.derive(0.5f));
g2d.setColor(UIManager.getColor("List.selectionBackground"));
g2d.fillRect(img.getWidth(), 0, img.getWidth(), img.getHeight());
g2d.dispose();
}
}
}
现在,您实际上可以预渲染它(有一个“正常”和“突出显示”图像),但这取决于您的需求
nb:我使用了当前外观中的 List.selectionBackground
颜色作为填充颜色,您可以将其替换为您想要的任何颜色
看看Trail: 2D Graphics和 Compositing Graphics了解更多详情
关于java - 如何在paintComponent方法中向图像添加颜色层?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32342607/