怎样用java绘制弧形文字
2017-01-10 · 百度知道合伙人官方认证企业
用java绘制弧形文字的方法是调用java 2d图形处理的api实现的。
完整代码如下:
// 引入需要的jar包
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
//定义一个类
public class FontPanel extends JPanel {
//定义一个画板,入参是图形g
public void paintComponent(Graphics g) {
super.paintComponent(g);
Font f = new Font("SansSerif", Font.BOLD, 14); 设置字体加粗
Font fi = new Font("SansSerif", Font.BOLD + Font.ITALIC, 14);设置字体加粗,斜体
FontMetrics fm = g.getFontMetrics(f); //得到当前的font metrics
FontMetrics fim = g.getFontMetrics(fi);//得到当前的font metrics
String s1 = "Java ";
String s2 = "Source and Support"; 定义字符串
String s3 = " java 字体变形学习";
int width1 = fm.stringWidth(s1); 设置宽度
int width2 = fim.stringWidth(s2);
int width3 = fm.stringWidth(s3);
Dimension d = getSize(); 设置二维图形的维度
int cx = (d.width - width1 - width2 - width3) / 2; 计算绘制字体的x轴
int cy = (d.height - fm.getHeight()) / 2 + fm.getAscent();计算绘制字体的y轴
g.setFont(f);
g.drawString(s1, cx, cy);
cx += width1;
g.setFont(fi);
g.drawString(s2, cx, cy);
cx += width2;
g.setFont(f);
g.drawString(s3, cx, cy);
}
main方法测试:
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("NotHelloWorld2");
frame.setSize(350, 200);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Container contentPane = frame.getContentPane();
contentPane.add(new FontPanel());
frame.show();
}
}
运行结果:
广告 您可能关注的内容 |