用Java在字符串中创建大小适中的图像 [英] Creating a sized image out of a string in Java

查看:255
本文介绍了用Java在字符串中创建大小适中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用基于实体的Java制作2D引擎。物理和精灵已经完成,但是我仍然需要能够使用 BaseText 类绘制文本。出于实验目的,我在 Renderer 类中使用以下代码(用于绘制所有精灵等):

I am making a 2d engine using Java based on entities. The physics and sprites are done, but I still need to be able to draw text with the BaseText class. For experimental purposes I am using the following code in the Renderer class (that handles drawing all the sprites and such):

BufferGraphics.drawString(((BaseText) Entity).getText(), (int) -(Origin.getX() * PositionTransform), (int) -Origin.getY());

但是,我希望能够将此代码移至 BaseText 实体的> setText(final String Text)方法,即,当调用它时,将创建一个包含指定文本的新图像(可能在

I would like to, however, be able to either move this code into the setText(final String Text) method of the BaseText entity, i.e. when it is called a new image is created containing the text specified (possibly in different fonts and sizes and such, I haven't decided).

我的问题是:我希望能够根据自己的喜好调整文本的大小(缩放)。 。将文本转换为图像也很好,因为我可以获取图像的尺寸并设置文本实体本身的大小。

My problem is this: I would like to be able to resize (scale) the text to my liking. It would also be nice to have the text converted to an image as I can get the dimensions of it and set the size of the text entity itself.

基本上,我需要遵循以下几条原则:

Basically, what I need follows something along these lines:


  1. 将所需的字符串输入到 setText 方法。

  2. 取字符串并将其绘制到图像上,并调整大小以使文本恰好适合其中。

  3. 设置此新图像到实体中的图片字段,以便引擎可以绘制它。

  1. Take desired string and feed it into the setText method.
  2. Take the string and draw it onto an image, sized so that the text will fit into it exactly.
  3. Set this new image to the Image field in the entity so that the engine can draw it.

这有可能吗?可能有一种方法可以使用 FontMetrics 类或任何可能被称为的类,但是我不确定,因为我以前从未使用过它。

Is this even possible? There may be a way to do this with the FontMetrics class or whatever it may be called, but I'm not so sure as I have not used it before.

编辑:让我澄清一下:我想根据设置为特定字体和大小的某些文本的大小创建,而不是调整文本大小

Edit : Let me clarify: I want to create a BufferedImage based on the size of some text set to a specific font and size, not size the text to fit an image.

编辑2:感谢安德鲁(Andrew)这么慷慨地提供了代码,我得以向引擎添加一些代码, ,只需应该即可。再次,但是,即使其中没​​有该drawRect,该图像还是保持透明或不被绘制。让我提供一些面包屑:-snip-

Edit 2: Thanks to this fellow Andrew, whom so graciously provided code, I was able to add some code to the engine that, by all means, just plain should work. Again, however, not even with that drawRect in there, the image either remains either transparent or somehow is not getting drawn. Let me supply some breadcrumbs: -snip-

愚蠢的事情是,所有其他精灵和图像以及类似内容都可以绘制,所以我不确定它怎么可能渲染器。
顺便说一句,那是paint()方法。

The stupid thing is that all the other sprites and images and such draw fine, so I am not sure how it could be the Renderer. By the way, that was the paint() method.

编辑3:

...

呃...

...

我的...
我是...

...

文字无法解释我用左手掌将自己束缚在脸上的困难程度。

Edit 3:
...
Uh...
...
Oh my.
I am...
...
Text can not explain how hard I belted myself in the face with my left palm.

BaseText.java

BaseText.java

@Override
public BufferedImage getImage() {return null;}

Renderer.java

Renderer.java

BufferedImage Image = Entity.getImage();

我是

a的白痴。

谢谢,安德鲁(Andrew),

I am
a huge idiot.
Thank you, Andrew, for that code. It worked fine.

编辑4:顺便说一下,这是我使用的最终代码:

Edit 4: By the way, here's the final code that I used:

public void setText(final String Text)
{
    Graphics2D Draw = (Graphics2D) Game.View.getBuffer().getDrawGraphics();
    FontMetrics Metrics = Draw.getFontMetrics();
    Rectangle2D Bounds = Metrics.getStringBounds(Text, Draw);
    BufferedImage NewImage = new BufferedImage((int) Bounds.getWidth(), (int) (Bounds.getHeight() + Metrics.getDescent()), BufferedImage.TYPE_INT_RGB);
    Draw = (Graphics2D) NewImage.getGraphics();
    Draw.setColor(new Color(0xAAFF0000));
    Draw.drawRect(0, 0, NewImage.getWidth(), NewImage.getHeight());
    Draw.drawString(Text, 0, (int) Bounds.getHeight());
    this.Image = NewImage;
    this.Text = Text;
    this.setSize(new Vector(NewImage.getWidth(), NewImage.getHeight()));
}


推荐答案


  1. 使用 FontMetrics GlyphView 或首选大小为 JLabel (方便获取显示格式化文本所需的大小。

  2. 在步骤1中调整字体的大小,直到适合为止。调用 BufferedImage.createGraphics()获得 Graphics2D 对象。将 String 涂上它。

  3. 我不明白第3点,因此不予评论。

  1. Use FontMetrics, GlyphView or the preferred size a JLabel (handy for getting the size needed to display formatted text.
  2. Adjust the sizes of the font in step 1 until it fits. Call BufferedImage.createGraphics() to get a Graphics2D object. Paint the String to that.
  3. I do not understand point 3, so won't comment.






这是使用 FontMetrics的方式 JLabel

import java.awt.*;
import java.awt.image.*;
import java.awt.geom.Rectangle2D;
import javax.swing.*;

class TextSize {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // Technique 1 - FontMetrics
                String s = "The quick brown fox jumps over the lazy dog!";
                BufferedImage bi = new BufferedImage(
                    1,
                    1,
                    BufferedImage.TYPE_INT_RGB);
                Graphics g = bi.getGraphics();
                FontMetrics fm = g.getFontMetrics();
                Rectangle2D b = fm.getStringBounds(s,g);
                System.out.println(b);
                bi = new BufferedImage(
                    (int)b.getWidth(),
                    (int)(b.getHeight() + fm.getDescent()),
                    BufferedImage.TYPE_INT_RGB);
                g = bi.getGraphics();
                g.drawString(s,0,(int)b.getHeight());

                JOptionPane.showMessageDialog(
                    null,
                    new JLabel(new ImageIcon(bi)));

                // Technique 3 - JLabel
                JLabel l = new JLabel(s);
                l.setSize(l.getPreferredSize());
                bi = new BufferedImage(
                    l.getWidth(),
                    l.getHeight(),
                    BufferedImage.TYPE_INT_RGB);
                g = bi.getGraphics();
                g.setColor(Color.WHITE);
                g.fillRect(0,0,400,100);
                l.paint(g);

                JOptionPane.showMessageDialog(
                    null,
                    new JLabel(new ImageIcon(bi)));
            }
        });
    }
}

这篇关于用Java在字符串中创建大小适中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆