JavaGraphics class drawing method, javagraphics class drawing

Source: Internet
Author: User

JavaGraphics class drawing method, javagraphics class drawing

The Graphics class provides the basic drawing method, and the Graphics class provides the basic geometric drawing method, mainly including: draw a line segment, draw a rectangle, draw a circle, draw a color image, draw an ellipse, draw an arc, draw a polygon, draw a string, and so on.

1. Draw a line segment: draw a line segment in a window. You can use the drawLine () method of the Graphics class:
/*** In the coordinate system of the image context, the current color is used in points (x1, y1) and (x2, y2) draw a line between them ** @ param x1 * x coordinate of the first vertex * @ param y1 * y coordinate of the first vertex * @ param x2 * x coordinate of the second vertex *@ param y2 * y coordinate of the second vertex */public abstract void drawLine (int x1, int y1, int x2, int y2)

For example, the following code draws a line segment between a vertex (3, 3) and a vertex (50, 50) and a vertex at a vertex (100,100.

G. drawLine (100,100,100,100, 50, 50); // draw a line segment g. drawLine (); // draw a vertex.
2. Draw a rectangle

There are two types of rectangles: Common and circular.

A. Draw A normal rectangle

There are two ways to draw a normal rectangle:

/*** Draw the border of the specified rectangle. The left and right sides of the rectangle are located in x and x + width. * The upper and lower edges are at y and y + height respectively. Draws the rectangle using the current color of the graphic context. */Public void drawRect (int x, int y, int width, int height)/*** fill in the specified rectangle. The left and right sides of the rectangle are located in x and x + width-1, respectively. * The upper and lower edges are located at y and y + height-1 respectively. * The resulting rectangle overwrites the width pixel width multiplied by the height pixel height. * Fill the rectangle with the current color of the graphic context. */Public abstract void fillRect (int x, int y, int width, int height)

Parameter x indicates the x coordinate of the image to be drawn, y indicates the y coordinate of the image to be drawn, width indicates the width of the image, and height indicates the height of the image.

The following code is an example of drawing a rectangle:

G. drawRect (80,100,); // draw a rectangular box g. setColor (Color. yellow); g. fillRect (20, 70, 20, 30); // draw a Color block with a rectangle

B. Draw a rounded rectangle.

There are two ways to draw a rounded rectangle:

/*** Use the current color of the image context to draw the border of the rounded rectangle. * The left and right sides of the rectangle are located in x and x + width. * The top and bottom edges of the rectangle are respectively y and y + height. */Public abstract void drawRoundRect (int x, int y, int width, int height, int arcWidth, int arcHeight)/*** fill the specified rounded corner rectangle with the current color. * The left and right sides of the rectangle are located in x and x + width-1, respectively. * The top and bottom edges of the rectangle are respectively y and y + height-1. */Public abstract void fillRoundRect (int x, int y, int width, int height, int arcWidth, int arcHeight)

The arcWidth parameter indicates the horizontal diameter of the four radians, and arcHeight indicates the vertical diameter of the four radians.

The following code is an example of drawing a rectangle:

G. drawRoundRect (10, 10, 40, 25); // draw a rounded rectangle g. setColor (Color. blue); g. fillRoundRect (80,100,100,100, 60, 40); // fill in a rounded rectangular block g. drawRoundRect (10,150, 40, 40, 40); // draw a circle g. setColor (Color. red); g. fillRoundRect (80,100,100,100,100,100); // draw a circle

You can use a rounded rectangle to draw a circle. When the width and height of the rectangle are equal, the horizontal diameter of the rounded arc is equal to the vertical diameter of the rounded arc, and equal to the width and height of the rectangle, the image is a circle. See the annotations in the above example. The first is the circle, and the last is the circle.

C. Draw a 3D rectangle

There are two ways to draw a 3D rectangle:

/*** Draw the 3-D highlighted border of the specified rectangle. * The side of the rectangle is highlighted, so that it is inclined and highlighted in the upper left corner. * The Color of the highlighted effect depends on the current color. * The resulting rectangle covers the area with width + 1 pixel width multiplied by height + 1 pixel height. */Public void draw3DRect (int x, int y, int width, int height, boolean raised)/*** draws a 3-D highlighted rectangle filled with the current color. * The side of the rectangle is highlighted, so that it is inclined and highlighted in the upper left corner. * The color used for the highlighted display is determined by the current color */public void fill3DRect (int x, int y, int width, int height, boolean raised)

The raised parameter indicates a boolean value used to determine whether a rectangle is displayed in a convex plane or a Concave Plane.

The following code is an example of highlighting a rectangle:

G. draw3DRect (80,100, 40, 25, true); // draw a 3D rectangular box g. setColor (Color. yellow); g. fill3DRect (20, 70, 20, 30, true); // draw a 3D rectangle with a color block
3. Draw an elliptical shape

The elliptical shape is determined by the horizontal and vertical axes of the elliptical shape. There are two methods to draw an elliptical shape:

/*** Draw an elliptical border. * Get a circle or an elliptic, which can be placed in a rectangle specified by the x, y, width, and height parameters. * The width and height of the covered area of an ellipse are + 1 pixel and 1 pixel respectively. */Public abstract void drawOval (int x, int y, int width, int height)/*** fill in the ellipse of the specified rectangular box with the current color. */Public abstract void fillOval (int x, int y, int width, int height)

You can also draw a circle using an elliptical method. When the horizontal axis and the vertical axis are equal, the circular shape is the circle.

The following code is an example of an elliptical image:

G. drawOval (10, 10, 60,120); // draw an elliptical g. setColor (Color. cyan); g. fillOval (, 30, 60, 60); // fill the circular Block g. setColor (Color. magenta); g. fillOval (15,140,100, 50); // fill the ellipse
4. Draw an arc

There are two methods to draw an arc:

/*** Draw an arc or elliptical arc border that overwrites the specified rectangle. */Public abstract void drawArc (int x, int y, int width, int height, int startAngle, int arcAngle)/*** fill in the arc or elliptical arc that overwrites the specified rectangle. */Public abstract void fillArc (int x, int y, int width, int height, int startAngle, int arcAngle)

The startAngle parameter indicates the starting angle, and arcAngle indicates the angle of arc spanning relative to the starting angle.

The obtained arc starts to span the arcAngle degree from startAngle. The angle is explained as follows: The 0 degree angle is at three o'clock. A positive value indicates clockwise rotation, and a negative value indicates clockwise rotation.

The center of the arc is the center of the rectangle. The origin of the rectangle is (x, y), and the size is specified by the width and height parameters.

The obtained arc covers the area with width + 1 pixel width multiplied by height + 1 pixel height.

The angle is relative to the non-Square area of the external rectangle, and the 45 degree angle always falls on the line from the center of the ellipse to the upper right corner of the external rectangle. Therefore, if the external rectangle is much longer than the other axis on one axis, the angle of the starting and ending points of the arc section will be larger along the long axis of the border.

The following code is an example of drawing an arc:

G. drawArc (10, 40, 90, 50, 0,180); // draw an arc g. drawArc (180,180, 40, 90, 50,); // draw an arc g. setColor (Color. yellow); g. fillArc (10,100, 40, 40, 0,-270); // fill in the elliptical g. setColor (Color. green); g. fillArc (60,110,110, 60,-90,-270); // fill in the 3/4 ellipse in the lower left corner.
5. Draw a polygon

A polygon is a closed plan connected by the first and end of multiple line segments. The x and y coordinates of the end points of a polygon line segment are stored in two arrays respectively. The polygon is connected by a straight line segment in the given coordinate sequence. The following two methods are commonly used to draw a polygon:

/*** Draws a closed polygon defined by arrays of x and y coordinates. Each pair of (x, y) coordinates defines a point. */Public abstract void drawPolygon (int [] xPoints, int [] yPoints, int nPoints);/*** fill in closed polygon defined by arrays of x and y coordinates. */Public abstract void fillPolygon (int [] xPoints, int [] yPoints, int nPoints)

Draw a polygon defined by nPoint line segments, where the first nPoint-1 line segment is 1 ≤ I ≤ from (xPoints [I-1], yPoints [I-1]) the line segment to (xPoints [I], yPoints [I. If the last vertex and the first vertex are different, the graph will automatically close by drawing a line segment between these two points.

The following code draws a polygon:

Int px1 [] = {50, 90,}; // The first and last point must be at the same time to draw a polygon int py1 [] = {, 50, 20 }; int px2 [] = {140,180,170,180,140,100,110,140}; int py2 [] = {5, 25, 35, 45, 25}; g. setColor (Color. blue); g. fillPolygon (px1, py1, 4); g. setColor (Color. red); g. drawPolygon (px2, py2, 8 );

You can also use a polygon object to draw a polygon. Create a Polygon object using Polygon, and then draw a Polygon with this object. The main methods of the Polygon class:

Polygon () // create an empty Polygon. Polygon (int [] xpoints, int [] ypoints, int npoints) // constructs and initializes a new Polygon based on the specified parameters. Public void addPoint (int x, int y) // Add a coordinate point to a Polygon object.

How to draw a Polygon using a Polygon object:

Public void drawPolygon (Polygon p) // draw a Polygon. Public void fillPolygon (Polygon p) // fill the Polygon.

For example, the following code draws a triangle and fills a yellow triangle. Note: If you use a polygon object to draw a closed polygon, the first and last points of the polygon do not need to overlap.

Polygon ponlygon1=new Polygon();    polygon1.addPoint(50,10);   polygon1.addPoint(90,50);   polygon1.addPoint(10,50);   g.drawPolygon(polygon1);    int x[]={140,180,170,180,140,100,110,100};  int y[]={5,25,35,45,65,45,35,25};   Polygon polygon2 = new Polygon(x,y,8);  g.setColor(Color.yellow);   g.fillPolygon(polygon2);
6. Draw strings

You can use the following methods to draw strings:

/*** Use the current font and color of the image context to draw the text given by the specified string. * The baseline of the leftmost character is located at the (x, y) Position of the graphic context coordinate system. */Public abstract void drawString (String str, int x, int y)

The following code is an example of creating a string:

G. setColor (Color. GREEN); g. setFont (new Font ("", Font. BOLD, 20); g. drawString ("string content drawn using a paint brush", 220,345 );
7. image painting

Common Methods for Drawing Images:

boolean drawImage(Image img, int x, int y, ImageObserver observer) boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer) boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer) 

Parameters:

Image img-the Image to be drawn.

Int x, int y-coordinates in the upper left corner of the image.

Int width, int height-width and height of the image.

Color bgcolor-background Color, that is, the Color below the image. This is useful if the image contains transparent pixels and will be displayed in the specified color background.

ImageObserver observer-an object that implements the ImageObserver interface. It registers the object as an image observer, so it is notified when any new information of the image is visible. Most components can simply specify this.

The Component can specify this as an image observer because the Component class implements the ImageObserver interface. When image data is loaded, its implementation calls the repaint method, which is usually what you expect.

The drawImage method returns the result as long as the image data to be displayed has been loaded. If you want to ensure that drawImage only draws the complete image, you need to track the image loading.

For example, to draw an image:

Image img = Toolkit.getDefaultToolkit().getImage("img/monster.gif");g.drawImage(img, 510, 5, 200, 200, Color.LIGHT_GRAY, this);
8. Erase rectangular blocks

When there is a blank rectangle in the middle of a colored image, you can use the background color to fill a rectangle, which is equivalent to using an "eraser" on the rectangle ". The implementation method is as follows:

/*** Clear the specified rectangle by filling the background color of the current drawing surface. */Public abstract void clearRect (int x, int y, int width, int height)

For example, the following code deletes the coloring of a rectangle in a circle:

g.setColor(Color.blue); g.fillOval(50,50,100,100);g.clearRect(70,70,40,55);
9. Define the graphic display area

A rectangle is used to represent the display area of the image. The image must be valid within the specified range. If the new coordinate value is not recalculated, the excess part will not be displayed automatically. The implementation method is as follows:

/*** Restrict the display of images in the specified area. The excess part is not displayed. When multiple restricted areas are covered, the intersection of restricted areas is obtained. */Public abstract void clipRect (int x, int y, int width, int height)

For example, the Code:

g.clipRect(0,0,100,50);g.clipRect(50,25,100,50);

Equivalent

g.clipRect(50,25,50,25);
10. Copy the image

The Graphics method copyArea () can be used to copy images. The format is:

/*** Dx and dy respectively indicate the number of pixel points to which the image is pasted to the original position offset. * The positive value is the offset to the right or down, and the negative value is the offset to the left or up. * The displacement reference point is the coordinate in the upper left corner of the rectangle to be copied. */Public abstract void copyArea (int x, int y, int width, int height, int dx, int dy)

For example, the following code copies all the parts of a rectangle and the other one.

g.drawRect(10,10,60,90);g.fillRect(90,10,60,90);g.copyArea(40,50,60,70,-20,80);g.copyArea(110,50,60,60,10,80);

Complete example:

Import java. awt. color; import java. awt. font; import java. awt. graphics; import java. awt. image; import java. awt. toolkit; import javax. swing. JFrame;/*** use Graphics class plotting ** @ author **/public class GraphicsDemo extends JFrame {public GraphicsDemo () {setSize (1000,600); setdefaclocloseoperation (EXIT_ON_CLOSE ); setLocationRelativeTo (null);} @ Override public void paint (Graphics g) {g. setColor (Color. RED); // draw a line segment g. drawLine (5, 5, 20,100); // draw point g. drawLine (20, 20, 20, 20); // draw a normal rectangular frame g. drawRect (30, 5,100,100); // fill the ordinary rectangle g. fillRect (140, 5,100,100); // draw the rounded rectangle g. drawRoundRect (250, 5,100,100, 30, 30); // fill in the rounded rectangle g. fillRoundRect (360, 5,100,100, 40, 40); // draw a 3D rectangle g. draw3DRect (5,110,100,100, false); // fill in the 3D rectangle g. fill3DRect (110,110,100,100, true); // draw an elliptical g. drawOval (220,110,100, 50); // fill in the elliptical g. fillOval (330,110, 30, 90); // draw an arc g. drawArc (5,220,100,100, 30,150); // fill in the ARC g. fillArc (110,220,100,100, 70,220); // draw a polygon int px [] = {210,220,270,250,240}; int py [] = {220,250,300,270,220}; g. drawPolygon (px, py, px. length); // fill in the polygon int px1 [] = {310,320,370,400,340}; int py1 [] = {220,250,300,270,220}; g. fillPolygon (px1, py1, px. length); // erase the block g. setColor (Color. BLUE); g. fillOval (5,330,100,100); g. clearRect (30,350, 30, 60); // specifies the graphic display area g. clipRect (130,380, 60, 60); g. clipRect (150,400, 50, 50); g. fillRect (1, 110,330,100,100); g. setClip (null); // draw string g. setColor (Color. GREEN); g. setFont (new Font ("", Font. BOLD, 20); g. drawString ("string content drawn using a paint brush", 220,345); // draw the Image img = Toolkit. getdefatooltoolkit (). getImage ("img/monster.gif"); g. drawImage (img, 510, 5,200,200, Color. LIGHT_GRAY, this); // copy the graph g. copyArea (0, 0,500,500,505,205);} public static void main (String [] args) {new GraphicsDemo (). setVisible (true );}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.