简体   繁体   English

在椭圆上画线

[英]Draw string on oval

I must write a text on an oval or circle I have this code(I found it on Stackoverflow) but I don't understand some points. 我必须在具有此代码的椭圆形或圆形上写文本(我在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));
    } 
}

and thanks 谢谢

Using information from the 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.

So you are telling the graphics to draw a circle where the top-left is at x - (half the width), y - (half the height). 因此,您要告诉图形绘制一个圆,其中左上角为x-(宽度的一半),y-(高度的一半)。 Reason being, it offsets the circle so the center of the circle is at (x, y) instead of the top-left. 原因是,它使圆偏移,因此圆的中心位于(x,y)而不是左上角。

getStringBounds getStringBounds

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

(Returns a rectangle that is big enough for the String) (返回一个足以容纳字符串的矩形)

Needless to say, the documentation is very helpful to look at when you are using various java classes. 不用说,当您使用各种Java类时,该文档对查看很有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM