当前位置:网站首页>Graphics2d class basic use
Graphics2d class basic use
2022-06-12 21:26:00 【Besieged city_ city with high walls】
Java Language in Graphics Class provides the basis for drawing all kinds of basic geometric figures , Expand Graphics Class provides a Graphics2D class , It has more powerful two-dimensional graphics processing capabilities , Provide 、 Coordinate transformation 、 More precise control of color management and text layout .
One 、 Drawing properties
Graphics2D Several methods are defined , Used to add or change the status attributes of a drawing . You can set and modify status attributes , Specify the brush width and how the brush is connected ; Set translation 、 rotate 、 Scale or trim transform shapes ; As well as setting the color and pattern of the filling graphics . Graph state attributes are stored in specific objects .
1. stroke attribute
stroke Property controls the width of the line 、 Pen style 、 Line segment connection mode or dash pattern . To set this attribute, you need to create BasicStroke object , Call again setStroke() Method to set . establish BasicStroke There are ways to object :
BasicStroke(float w): Specify line width w.
BasicStroke(float w,int cap, int join):
cap It is the end point :CAP_BUTT( No embellishment ),CAP_ROUND( Semicircular end ),CAP_SQUARE( Square end , The default value is ).
Join Define the connection method at the intersection of two line segments :JOIN_BEVEL( No embellishment ),JOIN_MTTER( Pointed end , The default value is ),JOIN_ROUND( Round end ).
2. paint attribute
paint Property controls the fill effect . First call the following method to determine the filling effect , Rational use setPaint() Method setting .
GradientPaint(float x1,float y1,Color c1,float x2,flaot y2,Color c2): from (x1,y1) To (x2,y2) Color from c1 Gradient to c2. among : Parameters c1,c2 This gradient is determined from the color c1 Gradient to color c2. Parameters x1,y1,x2,y2 Determines the strength of the gradient , That is, it is required to start from the point (x1,y1) Departure and arrival point (x2,y2), Color from c1 become c2.
GradientPaint(float x1,float y1,Color c1,float x2,float y2,Color c2,Boolean cyclic): If you want to gradient to the color of the end point and the start point , Should be cyclic Set to true.
3. transform attribute
transform Property is used to implement common graphic translation 、 Transform operations such as scaling and beveling . First create AffineTransform object , And then call setTransform() Method setting transform attribute . Last , With the specified attribute Graphics2D Object drawing graphics . establish AffineTransform There are ways to object :
getRotateinstrance(double theta): rotate theta radian .
getRotateInstance(double theta,dioble x,double y): Around the center of rotation (x,y) rotate .
getScaleInstance(double sx,double sy):x and y Press... Respectively in the direction sx,sy Scale transformation .
getTranslateInstance(double tx,double ty): Translation transformation .
getShearInstance(double shx,double shy): Chamfering transformation ,shx and shy Specify the cable tension .
You can also create one without transform Attribute AffineTransform object , Then use the following method to specify the drawing translation 、 rotate 、 Scale transform attributes .
transelate(double dx,double dy): Place the graph in x Axis translation dx Pixels .
scale(double sx,double sy): Graphics in x Axis scale sx times , Vertical scaling sy times .
rotate(double arc,double x, double y): The graph is represented by dots (x,y) Is the pivot point , rotate arc radian .
for example , establish AffineTransform object :
AffineTransform trans = new AffineTransform();
by AffineTransform Object specifies the rotation transform attribute around the point :
Trans.rotate(50.0*3.1415927/180.0,90,80);
Then for Graphics2D The object of g2d Set... With the above rotation transformation function “ paint brush ”:
Graphics2D g2d = (Graphics2D)g;g2d.setTranstorm(trans);
Last , With the graphic object as the parameter, call the Graphics2D Object's draw() Method . for example , Let there already be a conic object curve, The following code implements the above rotation function g2d Object to draw this conic :
g2d.draw(curve);
4. clip attribute
clip Property is used to achieve the clipping effect . Setting the clipping property calls setClip() Method to determine the Shape. More than one in a row setClip() Get the clipping area where they intersect .
##5. composit attribute
composit Property to set the effect of the overlapping area of the graph . First use the method AlphaComposite.getInstance(int rule, float alpha) obtain AlphaComposite object , Re pass setComposite() Method to set the blending effect .Alpha The range of values is 0.0f( Completely transparent )-0.1f( Completely opaque ).
Two 、Graphics2D Class drawing
Graphics2D Class remains Graphics Class , At the same time, many new methods have been added . The new method converts Geometry ( Line segment 、 Circle, etc. ) Draw as an object . stay java.awt.geom A series of classes declared in the package , Respectively used to create various body shape objects . There are mainly :
Line2D Line segment class ,RoundRectangle2D Rounded rectangle class ,Ellipse2D Ellipse class ,Arc2D Arc class ,QuadCurve2D Conic class ,CubicCurve2D Cubic curve class .
Use Graphics2D Class to draw a graph . First, redraw the method paintComponent() or paint() in , Set the parameter object g Cast to Graphics2D object ; then , Use the static method provided by the above graphic class Double() Create the object of the drawing ; Last , Call... With drawing object as parameter Graphics2D Object's draw() Method to draw the graph . For example, the following code uses Graphics2D A new method for drawing line segments and rounded rectangles :
package icu.xslblog;
import org.junit.Test;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
/** * @ClassName TestGraphics2D * @Description: TODO * @Author xsl * @Date 2020/11/2 14:26 */
public class Graphics2DTest {
@Test
public void test1() throws IOException {
// Get the source image input stream
FileInputStream imgFileStream = new FileInputStream("E:\\1.png");
// use imageIO Read the picture
Image image = ImageIO.read(imgFileStream);
// utilize BufferedImage, Load pictures into memory
int height = image.getHeight(null);
int width = image.getWidth(null);
BufferedImage bufImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// Get image object , To process the image
Graphics2D g = bufImg.createGraphics();
// Anti-Aliasing
RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
rh.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
rh.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
g.setRenderingHints(rh);
// Draw a line
g.drawImage(image, 0, 0, width, height, null);
Stroke s = new BasicStroke(10, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
g.setStroke(s);
// The new method
Line2D line = new Line2D.Double(30.0,30.0,340.0,30.0);
g.draw(line);
// The old way
//g.drawLine(30,50,300,300);
//g.drawLine(300,300,120,0);
//g.drawLine(120,0,30,50);
// To ensure the original quality output , use ImageWriter Output pictures
Iterator writers = ImageIO.getImageWritersByFormatName("png");
ImageWriter writer = (ImageWriter) writers.next();
// Specify the output path
File f = new File("E:\\test\\out.png");
ImageOutputStream outStream = ImageIO.createImageOutputStream(f);
// modify ImageWriteParam, Original quality output picture
ImageWriteParam imageWriteParam = writer.getDefaultWriteParam();
// take BufferedImage Convert to IIOImage, Then output the picture
IIOImage iioImage = new IIOImage(bufImg, null, null);
// Output
writer.setOutput(outStream);
writer.write(null,iioImage,imageWriteParam);
}
}
You can also use java.awt.geom Provided by the package Shape object , And use single precision Float Coordinate or double precision Double Coordinate creation Shape object , And then use draw() Methods to draw . for example , The following code first creates an arc object , Then draw an arc :
Shape arc = new Arc2D.Float(30,30,150,150,40,100,Arc2D.OPEN);
g2d.draw(arc)// Draw the graphic object you created earlier arc
3、 ... and 、Graphics2D Geometry class of
1. Line segment
// To declare and create a segment object, the starting point is (2,3), The end is (200,300)
Line2D line = new Line2D.Double(2,3,200,300);
2. rectangular
// Declare and create a rectangular object , The upper left corner of the rectangle is (20,30), Width is 300, Gao Shi 40
Rectangle2D rect = new Rectangle2D.Double(20,30,80,40);
3. Rounded rectangle
// The upper left corner is (20,30), Width is 130, Gao Shi 100, The long axis of the fillet is 18, The minor axis is 15.
RoundRectangle2D rectRound = new RoundRectangle2D.Double(20,30,130,100,18,15);
4. The ellipse
// top left corner (20,30), Width is 100, Gao Shi 50
Ellipse2D ellipse = new Ellipse2D.Double(20,30,100,50);
5. Arc
Arc2D arc1 = new Arc2D.Double(8,30,85,60,5,90,Arc2D.OPEN);
// The upper left corner of the circumscribed rectangle (10,30), wide 85, high 60, The starting angle is 5 degree , The termination angle is 90 degree
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);
Parameters Arc2D.OPEN、Arc2D.CHORD、Arc2D.PIE Respectively indicate that the arc is an open arc 、 Bow and pie arcs .
6. Quadratic curve
A conic is represented by a second-order polynomial :
y(x)=ax2+bx+c
A conic needs three points to determine : Starting point 、 Control points and end points .
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);
Method Double() Medium 6 The two parameters are the starting point of the conic 、 Control points and end points . above 3 The starting point and the ending point of the conic are the same .
7. Cubic curve
A cubic curve is represented by a third-order polynomial :
y(x)=ax3+bx2+cx+d
A cubic curve needs four points to determine : Starting point 、 Two control points and end points .
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);
Method Double() Medium 8 The three parameters are the starting point of the cubic curve 、 Two control points and end points .
The drawing process of general equation curve is controlled by a cycle . Loop through the values of the arguments , Calculate the function value according to the equation , Then make the necessary coordinate transformation : Translation transformation of origin positioning , Zoom transform for image reduction or enlargement , Get the image points of the curve , And draw this point . Take the following curve equation as an example :
y(x)=sin(x)+cos(x),
Part of the code drawn can be written as follows :
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,y2) It's an image point
x2=x0+x1*scale;y2=y0+y1*scale;
// Draw a dot as an image point
g.fillOval((int)x2,(int)y2,1,1);
}
Four 、 Practical application scenarios
Due to business needs, it needs to be on the background map
Dynamically write the title and author of the research paper and achieve automatic line feed
Synthesize the QR code of wechat applet on the background image
The effect is as follows

The code is as follows to write this tool class for convenience :
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import javax.imageio.ImageIO;
/** * <p>Title: CompositePicture</p> * <p>Description: Picture merge </p> */
public class CompositePicture {
/** * * @param path Load the address of the background picture * @param documentId The logo of my research paper The name used to compose the new graph This can be passed on or not according to your own needs * @param inputStream Wechat applet QR code Input stream I don't know how to generate wechat applet Wechat developer api Look up Or find resources online * @param title Research report title Is the text to be displayed on the background picture You can replace it with a user name or something according to your own needs * @param authorNameAndDate The author of the research report It is also the text to be displayed on the background picture You can replace it with a user name or something according to your own needs * @param fontSize Font size * @return */
public static String compositePicture(String path,Long documentId,InputStream inputStream, String title, String authorNameAndDate, int fontSize) {
String originalFilename = documentId+".png";
try {
// Load background image
BufferedImage imageLocal = ImageIO.read(new File(path + "share_background.png"));
int srcImgWidth = imageLocal.getWidth(null);
int srcImgHeight = imageLocal.getHeight(null);
// Load the QR code of wechat applet and convert it to BufferedImage
BufferedImage imageCode = ImageIO.read(inputStream);
// Take the background picture as the template
Graphics2D g = imageLocal.createGraphics();
// Eliminating text aliasing
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
// Add a user QR code to the template ( Address , The left margin , From the above , Image width , Picture height , Unknown )
g.drawImage(imageCode, 367, imageLocal.getHeight() - 170, 150, 150, null);
Font font1 = new Font(" Microsoft YaHei ", Font.BOLD, fontSize);// Add font property settings
g.setFont(font1);
Color color1 = new Color(100,0,0);
g.setColor(color1);
String waterMarkContent = title;
// Intercept the research report title Such as : Technology :MWC:5G And the design and production ideas of edge computing equipment are more clear Show as Technology :
g.drawString(waterMarkContent.substring(0,waterMarkContent.indexOf(":")+1),20,200);
// Intercept the research report title Such as : Technology :MWC:5G And the design and production ideas of edge computing equipment are more clear Show as MWC:5G And the design and production ideas of edge computing equipment are more clear
waterMarkContent=waterMarkContent.substring(waterMarkContent.indexOf(":")+1);
// Get the total length of watermark text
int fontlen = getWatermarkLength(waterMarkContent, g);
int line = fontlen / srcImgWidth;// How many lines should the text length be relative to the width of the picture
// Text overlay , Wrap overlay
int tempX = 20;
int tempY = 260;
int tempCharLen = 0;// Single character length
int tempLineLen = 0;// The total length of single line characters is temporarily calculated
System.out.println(" Total length of watermark text :" + fontlen + ", Image width :" + srcImgWidth + ", Picture height :" + srcImgHeight+ ", The number of characters :" + waterMarkContent.length()+ ", Number of lines of text :" + line+",x Initial coordinates :" + tempX+",y Initial coordinates :" + tempY);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < waterMarkContent.length(); i++) {
char tempChar = waterMarkContent.charAt(i);
tempCharLen = getCharLen(tempChar, g);// Get Title Length
if ((tempLineLen) >= srcImgWidth) {
g.drawString(sb.toString(), tempX, tempY);// The length is full of one line , Overlay text
sb.delete(0, sb.length());// Empty content , Re append
tempY += fontSize+10;// The length is full of one line ,Y The position of 10 character height
tempLineLen =0;
}
sb.append(tempChar);// Append character
tempLineLen += tempCharLen;
}
g.drawString(sb.toString(), tempX, tempY);// Finally, overlay the remaining text
Font font2 = new Font(" Microsoft YaHei ", Font.PLAIN, 23);// Add font property settings
g.setFont(font2);
Color color2 = new Color(255,255,255);
g.setColor(color2);
g.drawString(authorNameAndDate,20, imageLocal.getHeight() - 220);
g.dispose();
// Complete template modification
g.dispose();
// Determine whether the address path of the new file exists , If it doesn't exist, create one
File outputfile = new File(path+originalFilename);
if (!outputfile.getParentFile().exists()) {
outputfile.getParentFile().mkdirs();
}
// Generate a new composite user QR code and write a new picture
ImageIO.write(imageLocal, "png", outputfile);
} catch (Exception e) {
e.printStackTrace();
}
return originalFilename;
}
/** * * @param c The string that needs to be written on the background image * @param g Graphics2D java Composite picture The processing object of writing * @return */
public static int getCharLen(char c, Graphics2D g) {
return g.getFontMetrics(g.getFont()).charWidth(c)+3;
}
/** * Get the total length of watermark text * * @paramwaterMarkContent Watermark text * @paramg * @return Total length of watermark text */
public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
}
}
边栏推荐
- China hydraulic cylinder linear position sensor market trend report, technical dynamic innovation and market forecast
- What are the disadvantages of bone conduction earphones? Analysis of advantages and disadvantages of bone conduction earphones
- Graphics2D类基本使用
- 同花顺能开户吗,在APP上可以直接开通券商安全吗 ,证券开户怎么开户流程
- Data visualization - histogram
- Binary search
- Access control system based on RFID
- Inrelease: the following signature cannot be verified because there is no public key: no_ PUBKEY EB3E94ADBE1229CF
- Understanding of closures
- Delphi XE7的蓝牙 Bluetooth
猜你喜欢

Experiment 7-2-6 print Yanghui triangle (20 points)

leetcode:207. 课程表

Vs2017 environmental issues

GNS安装与配置
![Li Mu [practical machine learning] 1.4 data annotation](/img/e4/2593b1dec04476a9cc3b4af94dc189.jpg)
Li Mu [practical machine learning] 1.4 data annotation
![(4) Pyqt designs and implements the [factory production management system] order page - add, delete, modify and query (including source code analysis)](/img/71/47698193c0eb1a7fa39ceceb05b711.jpg)
(4) Pyqt designs and implements the [factory production management system] order page - add, delete, modify and query (including source code analysis)

Data visualization - Calendar chart

Leetcode: 210. Programme II

阅读笔记 Deep Hough Voting for 3D Object Detection in Point Clouds

@loadbalance annotation of resttemplate
随机推荐
Data visualization diagram microblog forwarding diagram
What did new do
Compréhension préliminaire des expressions régulières cognitives (regex)
(4) Pyqt designs and implements the [factory production management system] order page - add, delete, modify and query (including source code analysis)
Research Report on market supply and demand and strategy of hydraulic operating table industry in China
字符串基础知识
C language learning notes (II)
最简单ALV模板
leetcode:210. 课程表 II
模块八:设计消息队列存储消息数据的MySQL表
Shell script Basics
InRelease: 由于没有公钥,无法验证下列签名: NO_PUBKEY EB3E94ADBE1229CF
How to implement overloading in JS
Delphi XE7的蓝牙 Bluetooth
Gather function in pytorch_
lintcode:127 · 拓扑排序
Shell language
Do we media video, and share the necessary app for friendly new media operation
初步了解认识正则表达式(Regex)
Structure knowledge points all in