Java 2D API powerful and complex, but most of the time we just use Java.awt.Graphcis part of the function of the class. The following content will cover most common applications.
Graphics the methods in the class can be broadly divided into two categories:
- Draw and fill method for drawing basic graphics, text, and images;
- property setting method that controls the effect of drawing and padding. methods such as SetFont() and setcolor() belong to such methods.
Show the correspondence between these methods and images:
1. DrawString ()
Used to draw text:
g.DrawString ("Hello", 10, 10);
The parameters were:
- String to be drawn
- starting point x and the y coordinates
Import Java.applet.Applet; Import Java.awt.Graphics; Public class graphics_drawstring extends Applet { @Override Public void paint (Graphics g) { g . DrawString ("Hello Graphics", page, +); } } |
The output interface is as follows:
2. DrawImage
To draw an image:
Import Java.applet.Applet; Import Java.awt.Graphics; Import Java.awt.Image; Import Java.awt.Toolkit; Public class graphics_drawimage extends Applet { @Override Public void paint (Graphics g) { Image img = Toolkit. Getdefaulttoolkit (). GetImage (this. GetClass (). GetResource ("Th.png")); g . DrawImage (img, 0, 0, N, a, this); } } |
Th.png I randomly selected a picture, the output interface is as follows:
3. DrawLine, DrawArc, DrawRect, DrawOval, DrawPolygon
These methods are used to draw different shapes.
Depending on the requirements, you can choose from the following recommendations Graphics method of:
- whether to render the picture at its original size, or according to the specified Rectangle zoom picture;
- The transparent area of the picture, whether it is filled or not.
2D Graphics each of the points is required (x, y) coordinates are determined, so the drawing and filling methods require location information. For example, draw a line:
Graphics.drawline (int x1, int y1, int x2, int y2);
among them, (x1, y1) is the beginning of the line, (x2, y2) is the end of the line.
Java 2D API-2. Getting Started with Graphics