# Ten Tips For Getting Started with Graphics Programming

Friday Feb 13th 2015 by Manoj Debnath
Share:

Explore the ten crucial points to begin with graphics programming.

The term "Graphics" virtually refers to every visual artifact found on the computer screen. The field encompasses everything from the display of text, GUI elements of any window-based operating system, to images/pictures manipulation and animation, and so forth. Thus, the gamut of study is vast and quite enticing aesthetically, but, however appealing it may seem, there is more to it than meets the eye. The article shall try to give ten crucial points to begin with graphics programming.

## 1. Pixels and Coordinates

A computer screen is the ultimate playground of graphics. So, to begin with, we must first understand the coordinate system, which is a scheme for identifying every point on the screen. Painting a graphic symbol on the computer screen starts with the minuscule element called pixel (picture element), so a symbol or an image is nothing but a pattern of pixels in art form. In a simple terms, a pixel is a coincidental point of intersecting reference lines of a coordinate system when the computer screen is imagined as a simple sheet of graph paper.

Figure 1: The Cartesian coordinate system

Figure 2: Default coordinate system of computer screen. Units measured in pixels

## 2. Display Intricacies

Pixels drawn on the computer screen are mapped to an array of contiguous memory locations that hold the color of each pixel. At the simplest level, there is one memory bit for each pixel. Because memory bits have only two states (0 or 1), a single bit plane can produce only two colors, black or white. A modern display system uses multiple-bit planes for a single color value. For example, a 24-bit plane is grouped into 8 bits of a 3-bit plane. Each group can produce 28=256 shades of a single color, say red. Therefore, if we combine green and blue as well, we get a combination of (28)3=224=16,777,216 possible colors. Another display intricacy is the refresh rate of a computer screen. The refresh rate is the screen repaint job per time frame. For a continuous, flicker-less display, the minimum refresh rate required is 24 frames/second; in other words, the display should be repainted at least 24 times in a second to create an illusion of continuous image. 24 is the standard, magic number, to cheat our optic nerves into believing something is on always while in actuality it is continuously on and off. For example, if a light tied to a string is rotated very fast, you will create an optical illusion of a circle.

## 3. 2D and 3D Object Models

Two-dimensional (2D) objects are basically flat objects with only length and breadth, projected on a XY plane such as a sheet of paper. They become a line when turned sideways. The interesting part is the three-dimensional (3D) object model. It is projected mathematically on a XYZ plane that represents length, breadth, and depth respectively. A computer monitor displays everything in 2D format. The depth part that we see on the screen is actually an illusion, actualized with the help of light, shade effects, and visual angles. As should be obvious, to produce 3D effect, more number crunching is required by the processor and modeling becomes comparatively complex.

Figure 3: A 2D image

Figure 4: A 3D image

## 4. Animation

Animation simply refers to the time sequence of visual changes in a scene. It is an art and a science in its own right and do not always involve computers, but some steps in the development of an animation are well suited to a computer solution such, as object manipulation and rendering (for a 3D effect), camera motions, and the generation of in-between frames. They use some of the advanced features of computer graphics. There are specialized software packages that provide a special function for designing animation and processing individual objects. One common function provided by these packages is to store and manage an object database. Object shapes and associated parameters are stored and updated in the database and motions are generated according to specified constraints by using two-dimensional or three-dimensional transformations. One of the popular 2D animation packages is Adobe Flash and, for 3D modelling and animation, 3dsMax, Maya of Autodesk.

## 5. Math Skills

You cannot tread much ahead in graphics programming without extensive math skills. In fact, without math, one's graphics programming remains limited to things such as changing colors of objects or creating some objects through code for fun. Computer languages and graphics libraries are nothing but tools; mathematics churns your gray matter and helps in tweaking the numbers in such a manner that your creative imagination is turned into virtual reality. Of course, here I'm not talking about how to create a company logo, which requires more artistic skills than mathematics, but about the kind of software that helps the artist in creating a logo, such as PhotoShop. CorelDRAW, and the like. Now, mathematics is vast; one's obvious question is where to start? To begin with, let's narrow the area. Trigonometry, Matrices, Linear Algebra, and Calculus are a must. Start honing your skills if you are really serious; otherwise, you'll land nowhere, at least in the graphics field.

## 6. Drawing a Pixel in Java

In Java, by default, the upper left corner of a GUI component (for example, JPanel) is denoted as coordinates (0,0). Texts and shapes are displayed on the screen by specifying coordinates.

 Note: Java does not provide any pixel plotting method. What we can do is use the g.drawLine(100,100,100,100) method to plot a pixel on a GUI component.
```public class FunWithGraphics extends JPanel{

@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
drawXYAxis(g);
drawPixelAt(100, 100, g);
}

private void drawXYAxis(Graphics g){
int c=20;
g.setColor(Color.red);
g.drawLine(c, c, this.getWidth()-c, c);
g.drawString(">", this.getWidth()-c-2, c+5);
g.drawLine(c, c, c, this.getHeight()-c);
g.drawString("v", c-2, this.getHeight()-c+4);
}

private void drawPixelAt(int x, int y, Graphics g){
g.drawLine(x, y, x, y);
}

public static void main(String[] args) {
JFrame f=new JFrame("Graphics is Fun");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 300);
f.setVisible(true);
}
}
```

Figure 5: A pixel drawn at (100,100) position in a JPanel

## 7. Graphics Manager in Java

In Java, graphics objects come from from java.awt.Graphics, which is the manager of graphical context and responsible for drawing text, images, and other objects such as lines, ellipse, rectangles, and the like. Graphics is a abstract class because drawing performed in one platform (Operating System) is different from the other due to platform inherent graphic capabilities. For example, the way a PC running Windows draws a shape is different from that of Linux or other OS. So, distributing a concrete implementation of this class would mar any possibility of portability across platforms. When Java is implemented on each platform, a subclass of Graphics is created that implements drawing capabilities. The Graphics class keep this implementation hidden and provides an interface to give an illusion of platform-independent drawing capability. The method paintComponent is inherited from the Component class indirectly and takes a Graphics object as a parameter. This object receives a reference to an instance of the system-specific subclass that Graphics extends. Because drawing graphics in Java is a event-driven process, the paintComponent method is not called directly. When the GUI executes, the application container calls for this method each time an event occurs, such as minimized, maximized, component size changes, covering, and uncovering with another window, and so forth. However, to update the graphics dynamically, the paintComponent method can be re-executed with the repaint method.

## 8. Controlling Colors

The three primary colors—red, green, and blue—also called RGB, are the basis of all color components. They can be represented with integer values ranging from 0 to 255, or they can be of floating values in the range 0.0 to 1.0. The amount of a particular color depends on the RGB values. There are 256x256x256 color combinations available. The following Java program will demonstrate how to change the color of a component randomly as well as in a controlled manner.

```public class FunWithGraphics extends JFrame {
private final JButton randomButton =
new JButton("Set Random Color");
private final JButton optionButton =
new JButton("Change Color");

public FunWithGraphics() {
JPanel colorPanel = new JPanel();
JPanel buttonPanel =
new JPanel(new FlowLayout(FlowLayout.CENTER));
@Override
public void actionPerformed(ActionEvent e) {
Random r = new Random();
colorPanel.setBackground(new Color(r.nextInt(255), r
.nextInt(255), r.nextInt(255), r.nextInt(255)));
}
});

@Override
public void actionPerformed(ActionEvent e) {
Color c = JColorChooser.showDialog(FunWithGraphics.this,
"Choose any color", Color.red);
if (c != null)
colorPanel.setBackground(c);
}
});
}

public static void main(String[] args) {
JFrame f = new FunWithGraphics();
f.setTitle("Graphics is Fun");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 300);
f.setVisible(true);
}
}
```

Figure 6: Choosing color with the JColorChooser dialog

## 9. Creating Shapes

Creating different types shapes through programming is a basic exercise. They are not only fun but also provide some important insight into the intricacies of graphics programming. Here, you can test your understanding about graphical objects, screen coordinates, color models, and so on. Java provide provides the necessary APIs objects to start with things as the Graphics class, Graphics2D class, and several basic methods to create graphical shapes. The following code is a very simple one to give an idea how to implement it in Java. Although the code self explanatory, one interesting point worth mentioning here is that the translate method in the next code is used to translate the coordinate system in the middle of the screen (as in Figure 1); otherwise, Java follows the coordinate system of Figure 2 by default.

```public class FunWithGraphics extends JPanel {

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;
g2d.translate(this.getWidth() / 2,
this.getHeight() / 2);

Shape s1 = new Rectangle2D.Double(40, 50, 50, 50);
Shape s2 = new Ellipse2D.Double(10, 20, 20, 20);

Random r = new Random();
for (int i = 1; i <= 20; i++) {
g2d.setColor(new Color(r.nextInt(255),
0, 0, 255 - i));
g2d.rotate(Math.PI / 10.0);
g2d.fill(s1);

}

for (int i = 1; i <= 20; i++) {
g2d.setColor(new Color(r.nextInt(255),
r.nextInt(255), 0, 255 - i));
g2d.rotate(Math.PI / 10.0);
g2d.fill(s2);
}

}

public static void main(String[] args) {
JFrame f = new JFrame();
f.setTitle("Graphics is Fun");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 400);
f.setVisible(true);

}

}
```

Output:

Figure 7: Creating shapes with colors using Graphics2D

## 10. Simple Animation in Java

Animation is a feat achieved by showing very a rapid succession of a series of slightly different still images. Our persistence of vision is fooled into seeing a continuous action rather than a series of still images. For a simple animation in Java, we can achieve this with the help of a timer (as shown in the following code). More complex implementations use multiple threads, with one thread handling the modifications to the data structure and another thread doing the repainting job on the screen.

```public class SimpleAnimation extends JPanel
implements ActionListener {
private Shape s2 =
new Ellipse2D.Double(40, 50, 20, 20);
private Graphics2D g2d = null;
private Timer timer;
private double angle = 0;

public SimpleAnimation() {
timer = new Timer(10, this);
timer.start();
}

@Override
public void paintComponent(Graphics g) {
Random r=new Random();
super.paintComponent(g);
g2d = (Graphics2D) g;
g2d.translate(this.getWidth() / 2,
this.getHeight() / 2);
g2d.setColor(new Color(r.nextInt(255),
r.nextInt(255), r.nextInt(255), 255));
g2d.rotate(angle);
g2d.fill(s2);
}

public static void main(String[] args) {
JFrame frame =
new JFrame("Graphics is Fun");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
angle += 0.01;
repaint();
}
}
```

## Conclusion

With the preceding ten points, I tried to give some hint on graphics in general and its implementation in Java in particular. In doing so, I have only scratched the surface with an intention to whet your curiosity. Java, being a general purpose language, may not exactly fit for graphics programming, yet to begin with, I believe it is quite good. Once you get a penchant and want to dig deeper, you may have to stoop to C/C++, although there is no one best language for everything.

## References

Share:
Home
Mobile Site | Full Site