Drawing method of Java Graphics class __java

Source: Internet
Author: User

Graphics class provides basic drawing methods, graphics classes provide basic geometry rendering methods, mainly include: Draw line segments, draw a rectangle, draw a circle, draw the color of the graphic, draw the ellipse, draw arcs, draw polygons, draw strings and so on. Draw Segment

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

/**
 * Draw a line between the dots (x1, y1) and (x2, y2) in the coordinate system of this graphics context
 * * 
 @param x1
 *            The x-coordinate of the first point *
 @param y1
 *            the y-coordinate of the first point
 * @param x2
 *            The X coordinate of the second point *
 @param y2 *            the y-coordinate of the second point *
* Public abstr ACT void 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.
Draw a rectangle

There are two types of rectangles: plain and rounded.

draw an ordinary rectangle

There are two ways to draw a normal rectangle:

/**
 * Draws the border of the specified rectangle. The left and right edges of the rectangle are located at x and x + width respectively.
 * top and bottom edges are located at y and y + height respectively. Draws the rectangle using the current color of the graphics context.
*/public void DrawRect (int x, int y, int width, int height)

/**
 * Fills the specified rectangle. The left and right edges of the rectangle are located in x and X + width-1 respectively.
 * top and bottom edges are located at y and y + height-1 respectively.
 * The resulting rectangle covers the width pixel width multiplied by the height pixel area.
 * Fills the rectangle with the current color of the graphics context.
 *
/public abstract void FillRect (int x, int y, int width, int height)

Parameter x represents the x-coordinate of the graph to draw, and y represents the y-coordinate of the drawing, width represents the width of the graphic, and the height represents the graphic.

The following code is an example of a rectangular drawing:

G.drawrect (80,100,40,25); Draw rectangular wireframe

g.setcolor (color.yellow);
G.fillrect (20,70,20,30); Draw a rectangular shaded block

Draw rounded rectangles

There are two ways to draw rounded rectangles:

/**
 * Draws the border of the rounded rectangle with the current color of this graphics context.
 * The left and right edges of the rectangle are located at x and x + width respectively.
 * The top and bottom edges of the rectangle are located at y and y + height respectively.
 * * Public
abstract void drawroundrect (int x, int y, int width, int height,
        int arcwidth, int archeight)

/ * *
 * Fills the specified rounded rectangle with the current color.
 * The left and right edges of the rectangle are located in x and X + width-1 respectively.
 * The top and bottom edges of the rectangle are located at y and y + height-1 respectively.
 * * Public
abstract void fillroundrect (int x, int y, int width, int height,
        int arcwidth, int archeight)

The parameter arcwidth represents the horizontal diameter of 4 angular radians, and the archeight represents the vertical diameter of 4 angular radians.

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);//fill a rounded 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.

draw a three-dimensional rectangle

There are two ways to draw a three-dimensional rectangle:

/**
 * Draws the specified rectangle's highlight border.
 * The edges of the rectangle are highlighted so that the upper-left corner is angled and highlighted. 
 * The colors used to highlight the effect are determined according to the current color.
 * The resulting rectangle covers the width + 1 pixel width times the height + 1 pixel high area.
 *
/public void Draw3drect (int x, int y, int width, int height, Boolean raised)

/**
 * Draws a one-color highlight that fills with the current colour Shows the rectangle.
 * The edges of the rectangle are highlighted so that the upper-left corner is angled and highlighted.
 * The colors used to highlight the effect are determined by the current color
/public void Fill3drect (int x, int y, int width, int height, Boolean raised)

The parameter raised represents a Boolean value that determines whether the rectangle is displayed as a protruding plane or a concave plane.

The following code is an example of a highlighted rectangle:

G.draw3drect (80,100,40,25,true); Draw a 3D rectangular wireframe

g.setcolor (color.yellow); 
G.fill3drect (20,70,20,30,true); Draw a 3D rectangular shaded block
Draw Oval

The ellipse is determined by the horizontal and longitudinal axes of the ellipse. There are two ways to draw an ellipse:

/**
 * Draws the border of an ellipse.
 * Get a circle or ellipse that fits into the rectangle specified by the x, Y, width, and height parameters.
 * Ellipse Overlay area width + 1 pixels, height + 1 pixels.
/public abstract void DrawOval (int x, int y, int width, int height)

/**
 * Fills 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 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 Elliptical

G.setcolor (Color.cyan); G.filloval (100,30,60,60);//fill round block

g.setcolor (Color.magenta); G.filloval ( 15,140,100,50); Fill ellipse
Draw an arc

There are two ways to draw an arc:

/**
 * Draws an arc or elliptical arc border that overrides the specified rectangle.
 * * Public
abstract void DrawArc (int x, int y, int width, int height,
        int startangle, int arcangle)/

* *
 * Fills a circular or elliptical arc that overrides the specified rectangle.
 * * Public
abstract void Fillarc (int x, int y, int width, int height,
        int startangle, int arcangle)

The parameter startangle represents the starting angle, and the arcangle represents the angle of arc spanning relative to the starting angle.

The resulting arcs begin to span arcangle degrees from startangle. The interpretation of the angle is as follows: the 0-degree angle is at 3 o'clock position. Positive values indicate counter-clockwise rotation, and negative values indicate clockwise rotation.

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

The resulting arc covers the width + 1 pixel width times the height + 1 pixel high area.

The angle is specified relative to the non square area of the outer rectangle, and the 45-degree angle always falls on the line from the center of the ellipse to the upper-right corner of the outer rectangle. Therefore, if the external rectangle is much longer than the other axis on one axis, the angle of the start and end points of the arc segment will have a larger skew along the long axis of the border.

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); Filled with three-fourths elliptical

G.setcolor (Color.green) in the upper right corner; 
G.fillarc (60,110,110,60,-90,-270); Fills the three-fourths ellipse with the lower left corner
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:

/**
 * Draws a closed polygon defined by an array of x and Y coordinates. Each pair (x, y) coordinates define a point.
 * * Public
abstract void DrawPolygon (int[] xpoints, int[] ypoints, int npoints);

/**
 * Fills a closed polygon defined by an array of x and Y coordinates.
 * * Public
abstract void FillPolygon (int[] xpoints, int[] ypoints, int npoints)

Draws a polygon defined by a npoint segment, where the front nPoint-1 segments are 1≤i≤ from (xpoints[i-1, Ypoints[i-1]) to (xpoints[i), Ypoints[i]). If the last point is different from the first, the graph is automatically closed by drawing a line segment between the two points.

The following code is an example of a polygon drawing:

int px1[]={50,90,10,20};//The first end point, in order to draw polygon

int py1[]={10,50,50,20};

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

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 ()  //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 the Polygon object.

To draw a polygon using a polygon polygon object:

public void DrawPolygon (Polygon p)//Draw a polygon. Public

void FillPolygon (Polygon p)//fill polygon.

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.

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);
Draw a String

A common way to draw strings is:

/**
 * uses the current font and color of this graphics 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 graphics context coordinate system.
 *
/public abstract void drawstring (String str, int x, int y)

The following code is an example of drawing a string:

G.setcolor (color.green);
G.setfont (New Font ("italics", font.bold);
g.DrawString ("string content drawn with brushes", 220, 345);
Drawing Image

Common ways to draw images:

Boolean drawImage (image img, int x, int y, ImageObserver observer) 
Boolean drawImage (image img, int x, int y, int widt h, int height, imageobserver observer) 
boolean drawImage (Image img, int x, int y, Color bgcolor, ImageObserver observe R) 
boolean drawImage (Image img, int x, int y, int width, int height, Color bgcolor, imageobserver observer) 

Parameters:

Image img– images that need to be drawn.

int x, int y– image upper left corner coordinate.

int width, int height– the width and height of the image.

Color bgcolor– background color, that is, the colors underneath the image. This is useful if the image contains transparent pixels, and the image is displayed under the specified color background.

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

The reason the component can specify this as an image watcher is that the component class implements the ImageObserver interface. When the image data is loaded, its implementation calls the Repaint method, which is usually what you expect.

The DrawImage method returns whenever the image data to be displayed has been loaded. If you want to make sure DrawImage only draws the full image, then you need to track the image loading.

For example, draw a picture:

Image img = Toolkit.getdefaulttoolkit (). GetImage ("Img/monster.gif");
G.drawimage (IMG, 510, 5, MB, Color.light_gray, this);
Erase rectangular Block

When you need to have an empty rectangle in the middle of a shaded graph, you can fill a rectangular block with the background color, which is equivalent to using the eraser on the rectangular block. This is accomplished by:

/**
 * Clears the specified rectangle by filling it with 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 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);
Limit drawing 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 implementation method is:

/**
 * Limits the display of the graphic in the specified area 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.
 *
/public abstract void Cliprect (int x, int y, int width, int height)

For example, code:

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

Equivalent

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

The use of the Graphics class method Copyarea () enables the reproduction of the graphic, which uses the following format:

/**
 * dx and dy respectively denote the number of pixels that the graphic is to be offset from the original position,
 * positive to right or downward, and negative to left or upwards.
 * The reference point of the displacement is to copy the upper-left corner coordinates of the rectangle.
 * * Public
abstract void Copyarea (int x, int y, int width, int height, int dx, int dy)

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

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 drawing * * @author xiaoming */public class Graphicsdemo extends JFrame {public Graphicsdemo () {
        SetSize (1000, 600);
        Setdefaultcloseoperation (Exit_on_close);
    Setlocationrelativeto (NULL);
        @Override public void Paint (Graphics g) {G.setcolor (color.red);
        Draw line Segments G.drawline (5, 5, 20, 100);

        Draw Points G.drawline (20, 20, 20, 20);
        Draw ordinary Rectangular frame g.drawrect (30, 5, 100, 100);

        Fill the ordinary rectangular g.fillrect (140, 5, 100, 100);
        Draw rounded corners of rectangular g.drawroundrect (250, 5, 100, 100, 30, 30);

        Filled rounded rectangular g.fillroundrect (360, 5, 100, 100, 40, 40);
        Draw three-dimensional rectangular g.draw3drect (5, $, M, false);

        Filled three-dimensional rectangular g.fill3drect (the ",", ","); Draw Elliptic G.drawoval (220, 110, 100,50);

        Filled oval g.filloval (330, 110, 30, 90);
        Draw Arc G.drawarc (5, 220, 100, 100, 30, 150);

        Filled Arc G.fillarc (110, 220, 100, 100, 70, 220);
        Draw Polygon int px[] = {210, 220, 270, 250, 240};
        int py[] = {220, 250, 300, 270, 220};
        G.drawpolygon (px, py, px.length);
        Fill polygon int px1[] = {310, 320, 370, 400, 340};
        int py1[] = {220, 250, 300, 270, 220};

        G.fillpolygon (px1, Py1, px.length);
        Erasing block G.setcolor (Color.Blue);
        G.filloval (5, 330, 100, 100);

        G.clearrect (30, 350, 30, 60);
        Limited graphic display area G.cliprect (130, 380, 60, 60);
        G.cliprect (150, 400, 50, 50);
        G.fillrect (110, 330, 100, 100);

        G.setclip (NULL);
        Draws a string g.setcolor (Color.green);
        G.setfont (New Font ("italics", Font.Bold, 20));

        g.DrawString ("string content drawn with brushes", 220, 345); Draw image Images img = Toolkit.getdefaulttoolkit ().GetImage ("Img/monster.gif");

        G.drawimage (IMG, 510, 5, MB, Color.light_gray, this);
    Copy graphics G.copyarea (0, 0, 500, 500, 505, 205);
    public static void Main (string[] args) {new Graphicsdemo (). setvisible (True);
 }
}

Run Effect chart:

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.