Index

Table of contents

Graphics2D

draw rectangle
g.setColor(Color.GRAY);
g.fillRect(x, y, w, h);
draw text (y is bottom of text)
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setColor(Color.RED);
g.setFont(new Font("courier", Font.BOLD, 18));
g.drawString(message, x, y);
load an image
BufferedImage image = ImageIO.read(getClass().getResourceAsStream(path))
extract sub-image
raster.getSubimage(x, y, width, height);
draw an image
public void paintComponent(Graphics2D g) {
	Rectangle bounds = g.getClipBounds();
	g.drawImage(image, bounds.x, bounds.y, null);
	g.dispose();
}
scale, translate, rotate and paint image
g.translate(x, y);
g.rotate(Math.toRadians(degrees));
g.drawImage(image, -sprite.w / 2, -sprite.h / 2, sprite.w, sprite.h, null);
g.rotate(Math.toRadians(degrees));
g.translate(-x, -y);
draw rotated rectangle
AffineTransform identity = g.getTransform();
AffineTransform transform = new AffineTransform();
transform.rotate(Math.toRadians(degrees), x + w/2, y + h/2);
g.transform(transform);
g.setColor(Color.RED);
g.fillRect(x, y, w, h); // or any other shape or image
g.setTransform(identity);

trigonometry

degrees (360 scale) to radians
Math.toRadians(degrees);
split degrees in dx & dy (0 degrees is straight right)
int dx += Math.cos(Math.toRadians(degrees));
int dy += Math.sin(Math.toRadians(degrees));