【问题标题】:Any better way to draw string with outline in Java?在Java中用轮廓绘制字符串有什么更好的方法吗?
【发布时间】:2018-12-22 02:01:12
【问题描述】:

我需要在从图像中获得的Graphics 对象上绘制带有黑色轮廓的白色文本。我首先用黑色绘制相同的文本 4 次(向左或向右移动一个像素),然后用白色绘制一次。但是,如果轮廓需要超过 1 像素宽,这将无法正常工作,并且看起来确实像一个 hack。有没有更好的方法来做到这一点?

final BufferedImage image = ImageIO.read(new File("./test.jpg"));

Graphics g = image.getGraphics();
g.setFont(g.getFont().deriveFont(45F));

// coordinates
int x = 100;
int y = 100;

String text = "Hello world";

g.setColor(Color.black);
g.drawString(text, x + 1, y - 1);
g.drawString(text, x + 1, y + 1);
g.drawString(text, x - 1, y - 1);
g.drawString(text, x - 1, y + 1);

g.setColor(Color.white);
g.drawString(text, x, y);

截图:https://i.imgur.com/ONLsPxy.png

【问题讨论】:

    标签: java image graphics awt


    【解决方案1】:

    另一种选择是使用下面的代码创建一个形状,然后先绘制轮廓然后填充它:

            Graphics2D g2d = (Graphics2D)g;
            AffineTransform transform = g2d.getTransform();
            transform.translate(x, y);
            g2d.transform(transform);
            g2d.setColor(Color.black);
            FontRenderContext frc = g2d.getFontRenderContext();
            TextLayout tl = new TextLayout(text, g.getFont().deriveFont(45F), frc);
            Shape shape = tl.getOutline(null);
            g2d.setStroke(new BasicStroke(5f));
            g2d.draw(shape);
            g2d.setColor(Color.white);
            g2d.fill(shape);
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-09
      • 1970-01-01
      • 2013-02-27
      • 2019-04-20
      • 1970-01-01
      • 2023-03-20
      • 2021-09-07
      • 2021-03-27
      相关资源
      最近更新 更多