

G2.translate(getWidth() /2, getHeight() /2) Translate the origin to the center of window Now, here’s that same code using the implicit affine transformation of the rotate() method of Graphics2D. these x and y are relative to center of circle currently origin Int y = (int) (radius * Math.sin(theta)) * Draw a series of dots in a circular patternĭouble theta = 2 * Math.PI * ((double) i / NUM_DOTS) The easiest way to start drawing to the screen is simply to subclass the JComponent class and override the paintComponent(Graphics g) method. This example would be extremely difficult to replicate without affine transformations.įor the simple example, let’s draw dots in a circle pattern. Finally we will end with a more fully fleshed out example that really illustrates the power of affine transformations, rendering a simplified overhead view of the solar system. We’ll start with a simple example, once with standard Swing painting code, and once using affine transformations. With them you can express and code things more succintly, and clearly than is possible without them. If you do any work involving Graphics2D in Java (and if you work with Swing components, you implicitly do), knowing how to use affine transforms is extremely beneficial. Java has a class to represent these affine transformations, as well as shorthand methods to apply them to a Graphics2D context. See the following external sites for translation and rotation examples, shearing, scaling.


An affine transformation consists of one or more translation, rotation, scaling, and shearing transformations. Affine transformations are those that map lines to lines in the transformed coordinate space, and which preserve the relative distance between points. One can use matrices to perform all sorts of operations, such as transformations to move from one coordinate system to another, as well as a set known as affine transformations.

At the heart of all computer graphics lies linear algebra, and specifically matrix multiplication.
