在椭圆上绘制字符串

时间:2013-12-16 20:46:55

标签: java swing awt

我必须在椭圆形或圆形上写一个文字 我有这个代码(我在Stackoverflow上找到它),但我不明白一些观点。

import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.JPanel;

public class Panneau extends JPanel {
    @Override
    public void paintComponent(Graphics g){
        // Declaration 
        String text = "test";
        int x = 100, y = 50;
        int ovalWidth = 50, ovalHeight = 50;

        // Draw circle
        g.setColor(Color.blue);
        g.fillOval(x-ovalWidth/2, y-ovalHeight/2,ovalWidth, ovalHeight);
        // I don't understand why x-ovalwidth/2 and y-ovalheight/2

        // Put text into circle
        FontMetrics fm = g.getFontMetrics();
        double textWidth = fm.getStringBounds(text, g).getWidth();
        // What is the job of getstringbounds 
        g.setColor(Color.white);
        g.drawString(text, (int) (x - textWidth/2),(int) (y + fm.getMaxAscent() / 2));
    } 
}

并谢谢

1 个答案:

答案 0 :(得分:3)

使用Graphics Documentation

中的信息
fillOval( x, y, width, height)

x - the x coordinate of the upper left corner of the oval to be filled.
y - the y coordinate of the upper left corner of the oval to be filled.
width - the width of the oval to be filled.
height - the height of the oval to be filled.

所以你要告诉图形画一个圆圈,左上角是x - (宽度的一半),y - (高度的一半)。原因是,它偏移了圆圈,因此圆心位于(x,y)而不是左上角。

getStringBounds

Returns:
a Rectangle2D that is the bounding box of the specified String in the
specified Graphics context.

(返回一个足够大的字符串矩形)

毋庸置疑,在使用各种java类时,文档非常有用。