Java - 在图像中心绘制文本

发布于 2024-12-03 08:40:21 字数 372 浏览 2 评论 0 原文

我需要在图像的中心写入文本。要写的文本并不总是相同的。

我正在使用的代码在这里:

// Here I first draw the image
g.drawImage(img, 22, 15, 280, 225, null);
// I get the text 
String text = photoText.getText();
// Set the text color to black
g.setColor(Color.black);
// I draw the string 
g.drawString(text, 79.5F, 220.0F);

问题是文本不在图像的中心,我该怎么办?

我只需要在水平中心绘制文本。

I need to write text in the center of an image. The text to write is not always the same.

The code I'm using is here:

// Here I first draw the image
g.drawImage(img, 22, 15, 280, 225, null);
// I get the text 
String text = photoText.getText();
// Set the text color to black
g.setColor(Color.black);
// I draw the string 
g.drawString(text, 79.5F, 220.0F);

The problem is that the text isn't at the center of the image, what can I do?

I only need to draw the text at the horizontal center.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

末が日狂欢 2024-12-10 08:40:22

使用 JLabel 工作量较少,但 FontMetrics,如图 此处,将让您直接管理几何图形。

Using a JLabel is less work, but FontMetrics, shown here, will let you manage the geometry directly.

长梦不多时 2024-12-10 08:40:22

最简单的方法是使用带有图标和文本的 JLabel。然后将水平/垂直文本位置设置为 CENTER,文本将绘制在图像的中心。

从您的代码来看,您似乎正在尝试在图像底部附近绘制文本。在这种情况下,您可以使用带有 Icon 的 JLabel 作为容器。然后,您可以将布局设置为 BoxLayout 之类的内容,并添加另一个带有文本的标签。

这两种方法都不需要定制绘画。

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;

public class LabelImageText extends JPanel
{
    public LabelImageText()
    {
        JLabel label1 = new JLabel( new ColorIcon(Color.ORANGE, 100, 100) );
        label1.setText( "Easy Way" );
        label1.setHorizontalTextPosition(JLabel.CENTER);
        label1.setVerticalTextPosition(JLabel.CENTER);
        add( label1 );

        //

        JLabel label2 = new JLabel( new ColorIcon(Color.YELLOW, 200, 150) );
        label2.setLayout( new BoxLayout(label2, BoxLayout.Y_AXIS) );
        add( label2 );

        JLabel text = new JLabel( "More Control" );
        text.setAlignmentX(JLabel.CENTER_ALIGNMENT);
        label2.add( Box.createVerticalGlue() );
        label2.add( text );
        label2.add( Box.createVerticalStrut(10) );

        //

        JLabel label3 = new JLabel( new ColorIcon(Color.GREEN, 200, 150) );
        add( label3 );

        JLabel text3 = new JLabel();
        text3.setText("<html><center>Text<br>over<br>Image<center></html>");
        text3.setLocation(20, 20);
        text3.setSize(text3.getPreferredSize());
        label3.add( text3 );

        //

        JLabel label4 = new JLabel( new ColorIcon(Color.CYAN, 200, 150) );
        add( label4 );

        JTextPane textPane = new JTextPane();
        textPane.setText("Add some text that will wrap at your preferred width");
        textPane.setEditable( false );
        textPane.setOpaque(false);
        SimpleAttributeSet center = new SimpleAttributeSet();
        StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
        StyledDocument doc = textPane.getStyledDocument();
        doc.setParagraphAttributes(0, doc.getLength(), center, false);
        textPane.setBounds(20, 20, 75, 100);
        label4.add( textPane );
    }

    public static class ColorIcon implements Icon
    {
        private Color color;
        private int width;
        private int height;

        public ColorIcon(Color color, int width, int height)
        {
            this.color = color;
            this.width = width;
            this.height = height;
        }

        public int getIconWidth()
        {
            return width;
        }

        public int getIconHeight()
        {
            return height;
        }

        public void paintIcon(Component c, Graphics g, int x, int y)
        {
            g.setColor(color);
            g.fillRect(x, y, width, height);
        }
    }

    private static void createAndShowUI()
    {
        JFrame frame = new JFrame("LabelImageText");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new LabelImageText() );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

我的意思是我必须在图像中心写入文本,然后保存图像

您可以使用 屏幕图像创建任何组件的图像。这假设您正在 GUI 上显示图像和文本。

或者,如果您正在谈论只是读取图像,向图像添加文本,然后保存图像,那么您将需要创建一个 BufferedImage 并在其上绘制图像,然后在其上绘制文本。您将需要使用 Trashgod 提到的 FontMetrics 类。我的建议没有帮助。

The easy way is to use a JLabel with an Icon and Text. Then set the horizontal/vertical text position to CENTER and the text is painted in the center of the image.

From your code it looks like you are trying to paint the text near the bottom of the image. In this case you can use the JLabel with an Icon as a container. Then you can set the layout to something like a BoxLayout and add another label with the text.

No custom painting is required for either approach.

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;

public class LabelImageText extends JPanel
{
    public LabelImageText()
    {
        JLabel label1 = new JLabel( new ColorIcon(Color.ORANGE, 100, 100) );
        label1.setText( "Easy Way" );
        label1.setHorizontalTextPosition(JLabel.CENTER);
        label1.setVerticalTextPosition(JLabel.CENTER);
        add( label1 );

        //

        JLabel label2 = new JLabel( new ColorIcon(Color.YELLOW, 200, 150) );
        label2.setLayout( new BoxLayout(label2, BoxLayout.Y_AXIS) );
        add( label2 );

        JLabel text = new JLabel( "More Control" );
        text.setAlignmentX(JLabel.CENTER_ALIGNMENT);
        label2.add( Box.createVerticalGlue() );
        label2.add( text );
        label2.add( Box.createVerticalStrut(10) );

        //

        JLabel label3 = new JLabel( new ColorIcon(Color.GREEN, 200, 150) );
        add( label3 );

        JLabel text3 = new JLabel();
        text3.setText("<html><center>Text<br>over<br>Image<center></html>");
        text3.setLocation(20, 20);
        text3.setSize(text3.getPreferredSize());
        label3.add( text3 );

        //

        JLabel label4 = new JLabel( new ColorIcon(Color.CYAN, 200, 150) );
        add( label4 );

        JTextPane textPane = new JTextPane();
        textPane.setText("Add some text that will wrap at your preferred width");
        textPane.setEditable( false );
        textPane.setOpaque(false);
        SimpleAttributeSet center = new SimpleAttributeSet();
        StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
        StyledDocument doc = textPane.getStyledDocument();
        doc.setParagraphAttributes(0, doc.getLength(), center, false);
        textPane.setBounds(20, 20, 75, 100);
        label4.add( textPane );
    }

    public static class ColorIcon implements Icon
    {
        private Color color;
        private int width;
        private int height;

        public ColorIcon(Color color, int width, int height)
        {
            this.color = color;
            this.width = width;
            this.height = height;
        }

        public int getIconWidth()
        {
            return width;
        }

        public int getIconHeight()
        {
            return height;
        }

        public void paintIcon(Component c, Graphics g, int x, int y)
        {
            g.setColor(color);
            g.fillRect(x, y, width, height);
        }
    }

    private static void createAndShowUI()
    {
        JFrame frame = new JFrame("LabelImageText");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new LabelImageText() );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

I mean I have to write a text in the center of the image and then save the image

You can use Screen Image to create an image of any component. This assumes you are displaying the image and text on a GUI.

Or, if you are talking about just reading in an image adding text to the image and then saving the image, then you will need to create a BufferedImage and draw the image on it and then draw the text on it. You will need to use the FontMetrics class as mentioned by Trashgod. My suggestion won't help.

我一直都在从未离去 2024-12-10 08:40:22

一种可能的解决方案:在 JPanel 中绘制图像,确保将面板的首选大小设置为图像的大小,让 JPanel 使用 GridBagLayout,并将文本放置在添加到 JPanel 的 JLabel 中,而不使用 GridBagConstraints。这是将 JLabel 置于 JPanel 中心的一种方法。

One possible solution: draw the image in a JPanel, being sure to set the panel's preferredsize as the size of the image, have the JPanel use a GridBagLayout, and place the text in a JLabel that is added to the JPanel, without GridBagConstraints. This is one way to center the JLabel in the JPanel.

梦行七里 2024-12-10 08:40:22

我使用了 TextLayout 使文本正确居中:

example of generated image

以下是创建图像并将其另存为文件的方法:

int imgWidth = 250;
int imgHeight = 250;
var img = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);

Graphics2D g = img.createGraphics();

var backgroundColor = new Color(0, 150, 100);
g.setPaint(backgroundColor);
g.fillRect(0, 0, imgWidth, imgHeight);

var font = new Font("Arial", Font.PLAIN, 80);
g.setFont(font);
g.setPaint(Color.WHITE);

String text = "0";

var textLayout = new TextLayout(text, g.getFont(), g.getFontRenderContext());
double textHeight = textLayout.getBounds().getHeight();
double textWidth = textLayout.getBounds().getWidth();

g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
        RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

// Draw the text in the center of the image
g.drawString(text, imgWidth / 2 - (int) textWidth / 2,
                   imgHeight / 2 + (int) textHeight / 2);

String imgFormat = "png";
ImageIO.write(img, imgFormat, new File("/home/me/new_image." + imgFormat));

I used TextLayout to get the text properly centered:

example of generated image

Here's how to create the image and save it as a file:

int imgWidth = 250;
int imgHeight = 250;
var img = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);

Graphics2D g = img.createGraphics();

var backgroundColor = new Color(0, 150, 100);
g.setPaint(backgroundColor);
g.fillRect(0, 0, imgWidth, imgHeight);

var font = new Font("Arial", Font.PLAIN, 80);
g.setFont(font);
g.setPaint(Color.WHITE);

String text = "0";

var textLayout = new TextLayout(text, g.getFont(), g.getFontRenderContext());
double textHeight = textLayout.getBounds().getHeight();
double textWidth = textLayout.getBounds().getWidth();

g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
        RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

// Draw the text in the center of the image
g.drawString(text, imgWidth / 2 - (int) textWidth / 2,
                   imgHeight / 2 + (int) textHeight / 2);

String imgFormat = "png";
ImageIO.write(img, imgFormat, new File("/home/me/new_image." + imgFormat));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文