gpt4 book ai didi

java - 如何在另一个图像上绘制图像?

转载 作者:搜寻专家 更新时间:2023-11-01 01:02:25 26 4
gpt4 key购买 nike

我有一个关于随机城市交通网络模拟的 Java 项目,我想出了一个实现这个项目的方法,所以我将每个路口分成一个部分,该部分基本上是一个扩展的 JPanel 类(名为 Carrefour )...一切正常,直到我遇到如何绘制车辆并让它们通过道路的问题。

所以我的问题是如何在另一个图像(道路)上绘制图像(车辆图像)?

最佳答案

另一种不需要扩展组件的方法。

enter image description here

import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import java.util.Random;
import java.net.URL;
import javax.imageio.ImageIO;

public class ImageOnImage {

ImageOnImage(final BufferedImage bg, BufferedImage fg) {
final BufferedImage scaled = new BufferedImage(
fg.getWidth()/2,fg.getHeight()/2,BufferedImage.TYPE_INT_RGB);
Graphics g = scaled.getGraphics();
g.drawImage(fg,0,0,scaled.getWidth(),scaled.getHeight(),null);
g.dispose();

final int xMax = bg.getWidth()-scaled.getWidth();
final int yMax = bg.getHeight()-scaled.getHeight();

final JLabel label = new JLabel(new ImageIcon(bg));

ActionListener listener = new ActionListener() {

Random random = new Random();

public void actionPerformed(ActionEvent ae) {
Graphics g = bg.getGraphics();
int x = random.nextInt(xMax);
int y = random.nextInt(yMax);

g.drawImage( scaled, x, y, null );
g.dispose();

label.repaint();
}
};

Timer timer = new Timer(1200, listener);
timer.start();

JOptionPane.showMessageDialog(null, label);
}

public static void main(String[] args) throws Exception {
URL url1 = new URL("http://i.stack.imgur.com/lxthA.jpg");
final BufferedImage image1 = ImageIO.read(url1);

URL url2 = new URL("http://i.stack.imgur.com/OVOg3.jpg");
final BufferedImage image2 = ImageIO.read(url2);

//Create the frame on the event dispatching thread
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
new ImageOnImage(image2, image1);
}
});
}
}

关于java - 如何在另一个图像上绘制图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10055005/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com