|
楼主 |
发表于 2024-1-11 17:34:39
|
显示全部楼层
四川省成都市
import java.awt.BasicStroke; import java.awt.Canvas; import java.awt.Color; import java.awt.Container; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.InputStream; import java.awt.RenderingHints; import javax.swing.ImageIcon; import javax.swing.JFrame; public class Main extends JFrame { public Main() { setTitle("绘制几何图形"); setBounds(100, 200, 500, 500); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); Container c = getContentPane(); MyCanvas canvas = new MyCanvas(); c.add(canvas); } private class MyCanvas extends Canvas { @Override public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g;//新绘图类 Color c = Color.RED;//设置颜色属性 Stroke stroke = new BasicStroke(8);//设置画笔属性 Font font = null; try { InputStream is = new java.net.URL("https://resource.hellofont.cn/fonts/exhibition2/7925.ttf").openStream(); font = Font.createFont(Font.TRUETYPE_FONT, is).deriveFont(Font.BOLD, 24); } catch (Exception e) { e.printStackTrace(); } g2.setFont(font);//加载字体 g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); String text = "01234abc你好"; Rectangle2D rect = g2.getFontMetrics().getStringBounds(text, g2); int x = (int) ((getWidth() - rect.getWidth()) / 2); int y = (int) ((getHeight() - rect.getHeight()) / 2 + rect.getHeight()); g2.drawString(text, x, y); } } public static void main(String args[]) { Main m = new Main(); } } |
|