This is part of some test driver code i made for java2d:
package game2d.tests;
import game2d.imp.java2d.Java2DGameCanvas;
import game2d.imp.java2d.Java2DSpriteFactory;
import game2d.imp.java2d.Java2DSprite;
import game2d.space_invaders.GameStatistics;
import java.awt.Graphics2D;
import java.awt.Color;
import javax.swing.JFrame;
public class Java2DSpriteDrawTest {
public static void main(String[] args) {
new Java2DSpriteDrawTest();
}
private Java2DSprite sprite;
private JFrame frame;
private Java2DGameCanvas canvas;
Java2DSpriteFactory factory;
public Java2DSpriteDrawTest() {
canvas = new Java2DGameCanvas(800,600);
frame = Java2DGameCanvas.createFrame("",canvas,null);
factory = Java2DSpriteFactory.getSingleton();
frame.pack();
frame.setVisible(true);
start();
}
private Graphics2D g2;
public void start() {
sprite = Java2DSpriteFactory.getSingleton().getSprite("sprites/pleg.png");
GameStatistics.start();
//g2 = canvas.getDrawGraphics();
while (true) {
GameStatistics.update();
frame.setTitle(""+GameStatistics.fpsAvg);
update();
draw();
}
}
private double rot = 0.0;
public void update() {
rot += Math.PI/48.0;
}
public void draw() {
if (GameStatistics.skipTime < 0.0) {
System.err.println("gc");
return;
}
System.err.println(GameStatistics.skipTime);
g2 = canvas.getDrawGraphics();
g2.setColor(Color.black);
int w = canvas.getWidth();
int h = canvas.getHeight();
g2.fillRect(0,0,w,h);
g2.translate(w/2.0,h/2.0);
g2.rotate(rot);
g2.drawImage(sprite.getImage(), 0, 0, null);
g2.dispose();
canvas.flip();
}
}
I have set GameStatistics to update every 0.01 seconds, that is, 10 milliseconds and even so sometimes the test driver is skips drawing phases. Sometimes i get three skips in a row and i assumed it was because of garbage collection.
0.006366804002027493
0.007434334998833947
0.00677970600372646
0.007861329002480488
0.005753377001383342
0.007702932998654433
0.007847218003007583
gc
0.009391393003170379
gc
0.009567401000822429
gc
0.00907418400311144
0.005560730998695362
0.007317281000723597
0.0060004970073350705
0.005643210002745036
0.00722158500138903
0.006457108000176959
0.006683585001155734
0.0074173340035486035
It sucks that we have to dispose of the graphics context once rendering is finished. Is there a more eficient way to do this?
And how do we rotate an image around it’s center and not around its upper left corner using drawImage ?