你好)有一个问题是否有可能加速代码如下:
import java.awt.Canvas;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
public class Game extends Canvas {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 400;
private static final int HEIGHT = 400;
@Override
public void paint(Graphics g) {
super.paint(g);
int w = 20;
int h = 20;
int type = BufferedImage.TYPE_INT_ARGB;
BufferedImage image = new BufferedImage(w, h, type);
Graphics2D g2d = image.createGraphics();
g2d.setColor(Color.GREEN);
g2d.fillRect(0, 0, w, h);
g2d.dispose();
int MapWidth = image.getWidth(this);
int MapHeight = image.getHeight(this);
for (int s = MapWidth - MapWidth; s < MapWidth * 10; s++) {
for (int i = MapHeight - MapHeight; i < MapHeight * 10; i++) {
g.drawImage(image, s, i, (int) w, (int) h, this);
}
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.setSize(WIDTH, HEIGHT);
frame.add(new Game());
frame.setVisible(true);
}
});
}
}
他画了很长时间的照片。怎么加速?请帮助)
在绘制的图像之前,一个程序无法关闭。 有必要加快他们的绘图
答案 0 :(得分:1)
这很慢,因为在你的
中 for (int s = 0; s < MapWidth * 10; s++) {
for (int i = 0; i < MapHeight * 10; i++) {
g.drawImage(image, s, i, (int) w, (int) h, this);
}
}
对于400 * 400 MapWidth,MapHeight你正在绘制4000 * 4000个对象,所以你绘制了16 000 000个对象,它应该很慢。
如果你用它替换它,它会很快:):
for (int s = 0; s < MapWidth * 10; s += w) {
for (int i = 0; i < MapHeight * 10; i += h) {
g.drawImage(image, s, i, (int) w, (int) h, this);
}
}
答案 1 :(得分:0)
试试以下代码
import java.awt.Canvas;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
public class Game extends Canvas {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 400;
private static final int HEIGHT = 400;
@Override
public void paint(Graphics g) {
super.paint(g);
int w = 20;
int h = 20;
int type = BufferedImage.TYPE_INT_ARGB;
BufferedImage image = new BufferedImage(w, h, type);
Graphics2D g2d = image.createGraphics();
g2d.setColor(Color.GREEN);
g2d.fillRect(0, 0, w, h);
g2d.dispose();
int MapWidth = image.getWidth(this);
int MapHeight = image.getHeight(this);
for (int s = MapWidth - MapWidth; s < MapWidth * 10; s++) {
for (int i = MapHeight - MapHeight; i < MapHeight * 10; i=i+10) {
g.drawImage(image, s, i, (int) w, (int) h, this);
}
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.setSize(WIDTH, HEIGHT);
frame.add(new Game());
frame.setVisible(true);
}
});
}
}