这是我的代码,我使用了两张图片,一张用于背景图片,一张用于弹球动画,但是使用这段代码,球会在它的飞行轨迹中擦掉背景图片,所以我需要一些帮助,让我可以在transparent bufferedimage 然后将其作为背景图像的遮罩。提前致谢。
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class MainTest {
private final int TABLE_WIDTH = 300;
private final int TABLE_HEIGHT = 400;
private final int BALL_SIZE = 16;
private JFrame f = new JFrame("Pinball game");
Random rand = new Random();
private int ySpeed = 5;
private double xyRate = rand.nextDouble() - 0.5;
private int xSpeed = (int) (ySpeed * xyRate * 2);
private int ballX = rand.nextInt(200) + 20;
private int ballY = rand.nextInt(10) + 20;
private BackgroundPanel background = new BackgroundPanel();
private Foreground foreground = new Foreground();
private int preX = -1;
private int preY = -1;
BufferedImage image = new BufferedImage(TABLE_WIDTH, TABLE_HEIGHT, BufferedImage.TYPE_INT_ARGB);
Image back = new ImageIcon("res/cat1.jpg").getImage();
Graphics g = image.getGraphics();
Timer timer;
public void init() {
// Graphics2D g = image.createGraphics();
// image = g.getDeviceConfiguration().createCompatibleImage(30, 30, Transparency.TRANSLUCENT);
background.setBackground(new ImageIcon("res/cat1.jpg"));
background.setPreferredSize(new Dimension(TABLE_WIDTH, TABLE_HEIGHT));
foreground.setPreferredSize(new Dimension(TABLE_WIDTH, TABLE_HEIGHT));
background.add(foreground);
f.add(background);
ActionListener taskPerformer = evt -> {
if (ballX <= 0 || ballX >= TABLE_WIDTH - BALL_SIZE) {
xSpeed = -xSpeed;
}
else if (ballY <= 0 || (ballY >= TABLE_HEIGHT - BALL_SIZE)) {
ySpeed = -ySpeed;
}
万千封印
慕运维8079593
相关分类