Home Java javaTutorial Basic usage tutorial of Graphics2D class in Java

Basic usage tutorial of Graphics2D class in Java

Jan 17, 2017 pm 04:13 PM

The Java language extends the Graphics class to provide a Graphics2D class on the basis of the Graphics class that provides various basic geometric figures. It has more powerful two-dimensional graphics processing capabilities and provides coordinate conversion, color management and text layout. Waiting for more precise control.
Drawing Properties

Graphics2D defines several methods for adding or changing the state properties of graphics. You can specify the brush width and the connection method of the brush by setting and modifying the state attributes; setting the translation, rotation, scaling or trimming transformation graphics; and setting the color and pattern of the filled graphics, etc. Graphics state properties are stored with specific objects.

1. stroke attribute
The stroke attribute controls the width of the line, the pen style, the way the line segments are connected, or the dash pattern. To set this property, you need to create a BasicStroke object first and then call the setStroke() method to set it. The methods to create a BasicStroke object are:
BasicStroke(float w): Specify the line width w.
BasicStroke(float w, int cap, int join):
cap is the endpoint: CAP_BUTT (unmodified), CAP_ROUND (semi-circular end), CAP_SQUARE (square end, default value).
Join defines the connection method at the intersection of two line segments: JOIN_BEVEL (no modification), JOIN_MTTER (pointed end, default value), JOIN_ROUND (rounded end).

2. paint attribute
The paint attribute controls the filling effect. First call the following method to determine the filling effect, and use the setPaint() method to set it.
GradientPaint(float x1,float y1,Color c1,float x2,flaot y2,Color c2): From (x1,y1) to (x2,y2) color gradient from c1 to c2. Among them: parameters c1 and c2 determine the gradient color from color c1 to color c2. The parameters x1, y1, x2, y2 determine the strength of the gradient, that is, starting from point (x1, y1) to point (x2, y2), the color changes from c1 to c2.
GradientPaint(float x1, float y1, Color c1, float x2, float y2, Color c2, Boolean cyclic): If you want the gradient to end and be the color of the starting point, cyclic should be set to true.

3. transform attribute
The transform attribute is used to implement common transformation operations such as graphics translation, scaling, and beveling. First create an AffineTransform object, and then call the setTransform() method to set the transform attribute. Finally, the graphics is drawn using a Graphics2D object with specified properties. The methods for creating AffineTransform objects are:

getRotateinstrance(double theta): Rotate theta radian.

getRotateInstance(double theta,dioble x,double y): Rotate around the rotation center (x, y).

getScaleInstance(double sx,double sy): The x and y directions are transformed according to the proportion of sx and sy respectively.

getTranslateInstance(double tx,double ty): translation transformation.

getShearInstance(double shx,double shy): oblique transformation, shx and shy specify the oblique degree.

You can also create an AffineTransform object without a transform attribute first, and then use the following methods to specify the graphics translation, rotation, and scaling transformation attributes.

transelate(double dx,double dy): Translate the graphic by dx pixels in the x-axis direction.

scale(double sx,double sy): The graph is scaled sx times in the x-axis direction and sy times vertically.

rotate(double arc,double x, double y): The graph uses point (x, y) as the axis point and rotates arc radians.

For example, create an AffineTransform object:

AffineTransform trans = new AffineTransform();
Copy after login

Specify the point rotation transformation attribute for the AffineTransform object:

Trans.rotate(50.0*3.1415927/180.0,90,80);
Copy after login

Then set the "rotation transformation function" for the object g2d of Graphics2D with the above rotation transformation function "Brush":

Graphics2D g2d = (Graphics2D)g;g2d.setTranstorm(trans);
Copy after login

Finally, call the draw() method of the Graphics2D object with transformation function using the graphics object as a parameter. For example, assuming there is a quadratic curve object curve, the following code implements drawing this quadratic curve using the g2d object with the above rotation function:

g2d.draw(curve)
Copy after login

4. clip attribute
clip Properties are used to achieve clipping effects. To set the clipping attribute, you can call the setClip() method to determine the Shape of the clipping area. Multiple setClip() operations are performed consecutively to obtain the clipping area where they intersect.

5. composit attribute
The composit attribute sets the effect of the overlapping area of ​​graphics. First use the method AlphaComposite.getInstance(int rule, float alpha) to get the AlphaComposite object, and then set the mixing effect through the setComposite() method. Alpha values ​​range from 0.0f (fully transparent) to 0.1f (fully opaque).
Drawing methods of the Graphics2D class

The Graphics2D class still retains the drawing methods of the Graphics class, while adding many new methods. The new method draws geometric shapes (line segments, circles, etc.) as an object. A series of classes declared in the java.awt.geom package are used to create various body graphics objects. Mainly include:
Line2D line segment class, RoundRectangle2D rounded rectangle class, Ellipse2D ellipse class, Arc2D arc class, QuadCurve2D quadratic curve class, CubicCurve2D cubic curve class.

To draw a graphic using the new method of the Graphics2D class. First, in the redraw method paintComponent() or paint(), force the parameter object g into a Graphics2D object; then, use the static method Double() provided by the above graphics class to create the object of the graphics; finally, use the graphics object as a parameter Call the draw() method of the Graphics2D object to draw this graphic. For example, the following code uses the new method of Graphics2D to draw line segments and rounded rectangles:

Graphics2D g2d = (Graphics2D)g;//将对象g类型从Graphics转换成Graphics2D
Line2D line = new Line2D.Double(30.0,30.0,340.0,30.0);
g2d.draw(line);
RoundRectangle2D rRect = new RoundRectangle2D.Double(13.0,30.0,100.0,70.0,40.0,20.0);
g2d.draw(rRect);
Copy after login

You can also first use the Shape object provided by the java.awt.geom package and create a Shape object with single-precision Float coordinates or double-precision Double coordinates. , and then draw it using the draw() method. For example, the following code first creates an arc object and then draws the arc:

Shape arc = new Arc2D.Float(30,30,150,150,40,100,Arc2D.OPEN);
g2d.draw(arc)//绘制前面创建的图形对象arc
Copy after login

Geometry class of Graphics2D

Line segment

Line2D line = new Line2D.Double(2,3,200,300);//声明并创建线段对象
//起点是(2,3),终点是(200,300)
Copy after login

矩形

Rectangle2D rect = new Rectangle2D.Double(20,30,80,40);//声明并创建矩形对象,矩形的左上角是(20,30),宽是300,高是40
Copy after login

圆角矩形

RoundRectangle2D rectRound = new RoundRectangle2D.Double(20,30,130,100,18,15);
//左上角是(20,30),宽是130,高是100,圆角的长轴是18,短轴是15。
Copy after login

椭圆

Ellipse2D ellipse = new Ellipse2D.Double(20,30,100,50);
//左上角 (20,30),宽是100,高是50
Copy after login

圆弧

Arc2D arc1 = new Arc2D.Double(8,30,85,60,5,90,Arc2D.OPEN);
//外接矩形的左上角(10,30),宽85,高60,起始角是5度,终止角是90度
Arc2D arc2 = new Arc2D.Double(20,65,90,70,0,180,Arc2D.CHORD);
Arc2D arc3 = new Arc2D.Double(40,110,50,90,0,270,Arc2D.PIE);
Copy after login

参数Arc2D.OPEN、Arc2D.CHORD、Arc2D.PIE分别表示圆弧是开弧、弓弧和饼弧。
二次曲线
二次曲线用二阶多项式表示:

y(x)=ax2+bx+c
Copy after login

一条二次曲线需要三个点确定:始点、控制点和终点。

QuadCurve2D curve1 = new QuadCurver2D.Double(20,10,90,65,55,115);
QuadCurve2D curve2 = new QuadCurver2D.Double(20,10,15,63,55,115);
QuadCurve2D curve3 = new QuadCurver2D.Double(20,10,54,64,55,115);
Copy after login

方法Double()中的6个参数分别是二次曲线的始点、控制点和终点。以上3条二次曲线的开始点和终点分别相同。
三次曲线
三次曲线用三阶多项式表示:

y(x)=ax3+bx2+cx+d
Copy after login

一条三次曲线需要四个点确定:始点、两个控制点和终点。

CubicCurve2D curve1 = new CubicCurve2D.Double(12,30,50,75,15,15,115,93);
CubicCurve2D curve2 = new CubicCurve2D.Double(12,30,15,70,20,25,35,94);
CubicCurve2D curve3 = new CubicCurve2D.Double(12,30,50,75,20,95,95,95);
Copy after login

方法Double()中的8个参数分别是三次曲线的始点、两个控制点和终点。

一般的方程曲线的绘制过程用一个循环控制。通过循环产生自变量的值,按照方程计算出函数值,再作必要的坐标转换:原点定位的平移变换,图像缩小或放大的缩放变换,得到曲线的图像点,并绘制这个点。以绘制以下曲线方程为例:

Y=sin(x)+cos(x),x
Copy after login

绘制的部分代码可以写成如下:

double x0,y0,x1,y1,x2,y2,scale;
x0=100;y0=80;
scale =20.0;
for(x1=-3.1415926d;x1<=2*3.1415926d;x1+=0.01d){
  y1=Math.sin(x1)+Math.cos(x1);
  x2=x0+x1*scale;y2=y0+y1*scale;//(x2,y2)是图像点
  g.fillOval((int)x2,(int)y2,1,1);//画一个圆点作为图像点
}
Copy after login

更多Java中的Graphics2D类基本使用教程相关文章请关注PHP中文网!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte Mar 07, 2025 pm 06:09 PM

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How does Java's classloading mechanism work, including different classloaders and their delegation models? How does Java's classloading mechanism work, including different classloaders and their delegation models? Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

Node.js 20: Key Performance Boosts and New Features Node.js 20: Key Performance Boosts and New Features Mar 07, 2025 pm 06:12 PM

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

Iceberg: The Future of Data Lake Tables Iceberg: The Future of Data Lake Tables Mar 07, 2025 pm 06:31 PM

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed Mar 07, 2025 pm 05:52 PM

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

See all articles