1. The difference between Graphics 2D and Graphics
This Graphics 2D class extends the Graphics class to provide more complex control over geometry, coordinate transformation, color management and text layout. It is the basic class for rendering two-dimensional shapes, text and images on the Java(tm) platform.
tips: All in all, Graphics 2D is an enhanced version of Graphics, which enhances some advanced operations.
2. The specific use of setRenderingHint
Set the value of a single preference for the rendering algorithm. Tip categories include control over presentation quality and total time/quality tradeoffs during presentation.
tips: set up the processing methods of rendering image effects, such as anti-aliasing, color, difference and other effects processing algorithms. (I think anti-aliasing is useful now, but I will have different feelings in the future.) Here are two comparisons.
Unopened anti-aliasing
Open anti-aliasing
The following is the code implementation:
BufferedImage image = new BufferedImage(260, 80, BufferedImage.TYPE_INT_BGR); //Getting Graphics 2D Objects Graphics2D graphics = image.createGraphics(); //Open text anti-aliasing graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); //Setting fonts Font font = new Font("Algerian", Font.ITALIC, 40); graphics.setFont(font); //Write to the drawing board graphics.drawString("This is test!", 10, 60); graphics.dispose();
3. The Use of Stroke
Drawing a Shape is like drawing its outline with a brush of appropriate size and shape.
tips: The equivalent of a brush head to define the characteristics of the lines drawn; different types of lines are represented by setting different parameters. More details can be seen in this article about the use of Basic Stroke, which is described in detail.
Here's a small example I wrote myself (specifying a background map and drawing a tree):
package com.msw.test; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Polygon; import java.awt.RenderingHints; import java.awt.Stroke; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import javax.imageio.ImageIO; public class MyTest { public static void main(String[] args) throws IOException { BufferedImage image = new BufferedImage(400, 500, BufferedImage.TYPE_INT_BGR); BufferedImage image2 = ImageIO.read(new FileInputStream(new File("F:\\2.jpg"))); // Getting Graphics 2D Objects Graphics2D graphics = image.createGraphics(); graphics.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); //Set image2 as background image graphics.drawImage(image2, 0, 0, 400, 500,null); // Setting Brushes Stroke stroke = new BasicStroke(5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND); graphics.setStroke(stroke); // Set the color - Green graphics.setColor(Color.GREEN); //Painting trees graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Polygon polygon = new Polygon(); polygon.addPoint(200, 100); polygon.addPoint(180, 150); polygon.addPoint(220, 150); graphics.draw(polygon); polygon.reset(); polygon.addPoint(200, 150); polygon.addPoint(160, 200); polygon.addPoint(240, 200); graphics.draw(polygon); polygon.reset(); polygon.addPoint(200, 200); polygon.addPoint(140, 250); polygon.addPoint(260, 250); graphics.draw(polygon); polygon.reset(); polygon.addPoint(180, 250); polygon.addPoint(180, 300); polygon.addPoint(220, 300); polygon.addPoint(220, 250); graphics.draw(polygon); graphics.dispose(); File file = new File("F:\\1.jpg"); file.createNewFile(); FileOutputStream fos = new FileOutputStream(file); ImageIO.write(image, "jpg", fos); fos.close(); } }
Write on Graphics 2D pictures, calculate width and height, and position of fonts
As shown above, this is a string with Chinese and English characters. The width of Chinese characters is different from that of English characters. If I want to generate a wide and stiff picture, I need to calculate the width of each character and the appropriate height.
The class java.awt.FontMetrics gives a detailed introduction to the width and height of text.
Calculate the width of a string using fonts
public static int getWordWidth(Font font, String content) { FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font); int width = 0; for (int i = 0; i < content.length(); i++) { width += metrics.charWidth(content.charAt(i)); } return width; }
Calculate the maximum height of fonts used
FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font); int height = metrics.getHeight();
Pictures are the most appropriate place to write text.
Ascent is the highest height from the baseline to the top. It can also be used as the most useful height for font drawing.
graphics.drawString(content, 0, metrics.getAscent());
Test code
import sun.font.FontDesignMetrics; import javax.imageio.ImageIO; import java.awt.*; import java.awt.font.LineMetrics; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; /** * Created by zengrenyuan on 18/5/11. */ public class ImageTest { public static void main(String[] args) throws IOException { Font font = new Font("Microsoft YaHei", Font.BOLD, 32); String content = "Hello Java!"; FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font); int width = getWordWidth(font, content);//Calculate the width of the picture int height = metrics.getHeight();//Computational high BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = bufferedImage.createGraphics(); graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); //Set back to white graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight()); graphics.setFont(font); graphics.setColor(Color.BLACK); graphics.drawString(content, 0, metrics.getAscent());//Write words on pictures graphics.dispose(); write(bufferedImage, "/data/test.png"); } public static int getWordWidth(Font font, String content) { FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font); int width = 0; for (int i = 0; i < content.length(); i++) { width += metrics.charWidth(content.charAt(i)); } return width; } public static void write(BufferedImage bufferedImage, String target) throws IOException { File file = new File(target); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } try (OutputStream os = new FileOutputStream(target)) { ImageIO.write(bufferedImage, "PNG", os); } } }