A detailed approach to drawing using Java graphics Classes _java

Source: Internet
Author: User
Tags mixed

The Graphics class provides basic drawing methods, and GRAPHICS2D classes provide more powerful drawing capabilities. This section explains the graphics class, the next section explains Graphics2D.

The Graphics class provides basic geometry rendering methods, which include: drawing segments, drawing rectangles, drawing circles, drawing with color graphics, drawing ellipses, drawing arcs, drawing polygons and so on.

1. Draw Line
To draw a line segment in a window, you can use the DrawLine () method of the Graphics class:

  DrawLine (int x1,int y1,int x2,int y2)


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

  G.drawline (3,3,50,50)//Draw a line segment
  g.drawline (100,100,100,100);//Draw a point.

2. Draw a rectangle
There are two kinds of rectangles: plain and rounded.
(1) There are two ways to draw an ordinary rectangle:
DrawRect (int x,int y,int width,int height): A rectangle enclosing the wireframe. where parameters x and y Specify the position of the upper-left corner, the width of the parameter and height are the width and height of the rectangle.
FillRect (int x,int y,int width,int height): Fills a rectangle with a predetermined color, resulting in a shaded rectangular block.
The following code is an example of a rectangular drawing:

 G.drawrect (80,100,40,25);//Draw wireframe
 G.setcolor (color.yellow); G.fillrect (20,70,20,30);//Draw coloring Blocks

(2) There are two ways to draw rounded rectangles:
Drawroundrect (int x,int y,int width, int height, int arcwidth, int archeight): A rounded rectangle surrounded by lines. Where the parameters x and y Specify the position of the upper-left corner of the rectangle, the width of the parameter and the heigth are the width and height of the rectangle, and the Arcwidth and archeight are the transverse diameters of the rounded arcs and the longitudinal diameters of the fillet arcs respectively.
Fillroundrect (int x,int y,int width,int height,int arcwidth,int): A rounded rectangle filled with a predetermined color. The meaning of each parameter is the same as the previous method.
The following code is an example of a rectangular drawing:

 G.drawroundrect (10,10,150,70,40,25)//Draw a rounded rectangle
 g.setcolor (color.blue); G.fillroundrect (80,100,100,100,60,40) //apply a rounded corner rectangular block
 g.drawroundrect (10,150,40,40,40,40);//Draw round
 G.setcolor (color.red); G.fillroundrect ( 80,100,100,100,100,100)//Draw round block


You can draw circles with rounded rectangles, when the width and height of the rectangle are equal, and the transverse diameter of the fillet arc is equal to the longitudinal diameter of the fillet arc, which is equal to the width and height of the rectangle, and the circle is drawn. See the note in the above example, the first one is a circle, the latter is a circular block.

3. Draw three-dimensional rectangle
There are two ways to draw a three-dimensional rectangle:
Draw3drect (int x,int y,int width,int height, Boolean raised): Draw a highlighted rectangle. where x and y specify the position of the upper-left corner of the rectangle, the parameter width and height are the width and height of the rectangle, and the parameter raised is prominent or not.
Fill3drect (int x,int y,int width,int Height,boolean raised): Fills a highlighted rectangle with a predetermined color.
The following code is an example of a highlighted rectangle:

 G.draw3drect (80,100,40,25,true)//Draw a wireframe
 g.setcolor (color.yellow); G.fill3drect (20,70,20,30,true);//Draw a shaded block

4. Draw Oval
The ellipse is determined by the horizontal and longitudinal axes of the ellipse. There are two ways to draw an ellipse:
DrawOval (int x,int y,int width,int height): is a drawing with a line around the oval. where parameter x and parameter y specify the position of the upper-left corner of the ellipse, the parameter width and height are the horizontal and vertical axes.
Filloval (int x,int y,int width,int height): is an ellipse filled with a predetermined color, and is a shaded block. You can also draw a circle in an elliptical way, and when the horizontal and vertical axes are equal, the ellipse is rounded.
The following code is an example of an elliptical picture:

 G.drawoval (10,10,60,120)//Draw ellipse
 G.setcolor (Color.cyan); G.filloval (100,30,60,60);//painted round block
 g.setcolor ( Color.magenta); G.filloval (15,140,100,50);//Painted Oval

5. Draw the Arc
There are two ways to draw an arc:
DrawArc (int x,int y,int width,int height,int startangle, int arcangle): An arc line that draws part of the ellipse. The center of the ellipse is the center of its outer rectangle, where the parameter is the upper-left corner coordinate (x,y) of the outer rectangle, width is wide, and height is heigh. The unit of the parameter startangle is "degree", The starting angle of 0 degrees is the 3 o'clock azimuth. Parameter StartAngle and Arcangle represent the arc of Arcangle degree from the angle of startangle, and the agreement is that the positive degree is counterclockwise and the negative degree is clockwise, for example--90 degrees is the 6 o'clock orientation.
Fillarc (int x,int y,int width, int height, int startangle, int arcangle): The color set by the SetColor () method to draw part of the shaded ellipse.
The following code is an example of an arc drawing:

 G.drawarc (10,40,90,50,0,180)//Draw round arc
 G.drawarc (100,40,90,50,180,180),//Draw round arc
 G.setcolor (Color.yellow); G.fillarc (10,100,40,40,0,-270)//Fill missing three-fourths ellipse g.setcolor (color.green) in the upper right corner
 ; G.fillarc (60,110,110,60,-90,-270) ;//Fill missing three-fourths ellipse in lower left corner

6. Draw a polygon
A polygon is a closed floor plan that is connected by a number of line segments. The x and Y coordinates of the end of the polygon segment are stored in two arrays, and the polygon is connected with a straight segment in the order of the given coordinates. Here are two common ways to draw polygons:
DrawPolygon (int xpoints[],int ypoints[],int npoints): Draw a polygon
FillPolygon (int xpoints[],int ypoints[],int npoints): color-shaded polygons with Method SetColor (). Where the array xpoints[] stores the X coordinate point, ypoints[] stores the y-coordinate point, and the npoints is the number of coordinate points.

Note that the above method does not automatically close the polygon, to draw a closed polygon, the last point of the given coordinate point must be the same as the 1th. The following code implements populating a triangle and drawing a eight-side shape.

 int px1[]={50,90,10,50};//The first end point, in order to draw polygon 
 int py1[]={10,50,50,10};
 int px2[]={140,180,170,180,140,100,110,140};
 int py2[]={5,25,35,45,65,35,25,5};
 G.setcolor (Color.Blue);
 G.fillpolygon (px1,py1,4);
 G.setcolor (color.red);
 G.drawpolygon (px2,py2,9);

You can also draw polygons with polygon objects. Create a Polygon object with the Polygon class polygon, and then draw the polygon with this object. The main methods of the Polygon class are:

    • Polygon (): Creates a Polygon object with no coordinate points at the moment.
    • Polygon (int xpoints[],int ypoints[],int npoints): Creates a Polygon object with the specified coordinate point.
    • Addpoint (): Adds a coordinate point to the Polygon object.
    • DrawPolygon (Polygon P): Draws a polygon.
    • FillPolygon (Polygon P): Fills the polygon with the specified color.

For example, the following code, draw a triangle and fill a yellow triangle. Note that drawing a closed polygon with a polygon object does not require the first end point to coincide.

 int x[]={140,180,170,180,140,100,110,100};
 int y[]={5,25,35,45,65,45,35,25};
 Polygon ponlygon1=new Polygon ();
 Polygon1.addpoint (50,10);
 Polygon1.addpoint (90,50);
 Polygon1.addpoint (10,50);
 G.drawpolygon (polygon1);
 G.setcolor (color.yellow);
 Polygon polygon2 = new Polygon (x,y,8);
 G.fillpolygon (Polygon2);

7. Erase Rectangular Block
When you need to have an empty rectangle in the middle of a shaded graphic, you can fill a rectangular block with the background color, which is equivalent to using the eraser on the rectangular block. The implementation method is:
Clearrect (int x,int y, int width,int height): Erases the coloring of a rectangular block specified by a parameter.
For example, the following code implements the coloring of a rectangular block in a circle:

 G.setcolor (Color.Blue);
 G.filloval (50,50,100,100); G.clearrect (70,70,40,55);

8. Limit the mapping of the display area
A rectangle that represents the display area of the graphic, requires that the graphic be valid within the specified range, does not recalculate the new coordinate value, and that the automatic implementation exceeds the portion of the display. The method is cliprect (int x,int y,int width,int height), which restricts the display of the graphic within the specified range and does not appear in excess of the section. When more than one restricted area has an overlay, the intersection area of the restricted area is obtained. For example, code:

 G.cliprect (0,0,100,50); G.cliprect (50,25,100,50);


Equivalent

 G.cliprect (50,25,50,25);

9. Copy Graphics
The use of the Graphics class method Copyarea () enables the reproduction of the graphic, which uses the following format:
Copyarea (int x,int y,int width,int height, int dx, int dy), dx and dy, respectively, represent the number of pixels to which the graphic is pasted to the original position, positive to right or down, and negative to left or upwards. The reference point for the displacement is to copy the upper-left corner coordinate of the rectangle.

For example, the following code sketch is copied, making the entire portion of one rectangle, and the other rectangle, individually.

 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);

The example applet overrides the update () method, clearing only the circle block, not clearing the text, and the window displays a constantly moving red square.

Import java.applet.*;
Import java.awt.*;
public class Example7_3 extends applet{
 int i=1;
 public void init () {
 setbackground (color.yellow);
 }
 public void Paint (Graphics g) {
 i = i+8; if (i>160) I=1;
 G.setcolor (color.red); G.fillrect (i,10,20,20)
 ; g.DrawString ("I am learning the update () method", 100,100);
 try{
  Thread.Sleep (MB);
 catch (Interruptedexception e) {}
 repaint ();
 }
 public void Update (Graphics g) {
 g.clearrect (i,10,200,100);//Do not clear "I am learning Update () method"
 paint (g);
 }

General drawing programs to inherit JFrame, define a jframe window subclass, and inherit JPanel, define a JPanel subclass. Redefine the method Paintcomponent () in the JPanel subclass to invoke the drawing method in this method, drawing various shapes.

"Example" uses an XOR drawing mode application.

Import javax.swing.*;
Import java.awt.*; public class Example7_4 extends jframe{public static void Main (String args[]) {Graphicsdemo mygraphicsframe = new Graph
 Icsdemo ();
 } class Shapespanel extends jpanel{Sharpespanel () {setbackground (color.white);
 public void Paintcomponent (Graphics g) {super.paintcomponent (g); SetBackground (Color.yellow); The background color is yellow g.setxormode (color.red);
 Sets the XOR drawing mode, the color is Red g.setcolor (Color.green); G.fillrect (20, 20, 80, 40);
 The actual color is green + yellow mixed color = Gray G.setcolor (color.yellow); G.fillrect (60, 20, 80, 40);
 The latter half is Yellow+yellow=read, the first half is yellow+ Gray G.setcolor (Color.green); G.fillrect (20, 70, 80, 40);
 The actual color is the mixed color of the Green+yellow = Gray.
 G.fillrect (60, 70, 80, 40);
 The first half is (green+yellow) +gray = background color, the latter half is Green+yellow = Gray G.setcolor (color.green); G.drawline (80, 100, 180, 200); The line is Green+yellow = Gray g.drawline (100, 100, 200, 200);
 Ditto/* To draw partially overlapping lines. The middle segment of the original line is Gray + Gray = background color, and the extension part is green+yellow=gray.*/g.drawline (140, 140, 220, 220); G.setcolor (Color.yellow); //analyze the following line color changes, overlapping with previous forces G.drawline (20, 30, 160, 30);
 G.drawline (20, 75, 160, 75);
 The class Graphicsdemod extends jframe{public Graphicsdemo () {This.getcontentpane (). Add (New Shapespanel ());
 SetTile ("Basic Drawing Method Demo");
 SetSize (300, 300);
 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.