gpt4 book ai didi

java - 使用java格式化: Mixing text and pictures

转载 作者:行者123 更新时间:2023-11-30 04:29:31 25 4
gpt4 key购买 nike

我有一段特定的文本,我想为用户注释。不幸的是我什至不知道从哪里开始。我的算法给出了字符串上的一个范围作为输出。我想要的是这样的:

example

我需要两种方法来标记角色(蓝线,红线),也许还可以反转角色(给角色不同的背景),或者让他们变胖。特别困难的是将图片(此处由两个黑点表示)与字符对齐。由于字符应该在 Courier New 中,我可以知道在哪里放置偏移量,但我似乎无法做到这一点。

最后,我必须在 X 个字符后应用一个中断并开始一个新行,就像图片中一样。我还没有找到任何如何用 java 来解决这个问题的例子。使用 python,我可以使用 ImageDraw,但我对 java 却束手无策。

是否可以在屏幕上的 Canvas 上显示此内容并将其导出为 svg 或 pdf?我不知道有什么图书馆可以做到这一点。因此,我很高兴收到一些建议/示例。

最佳答案

关键是处理FontMetrics API。你能做的最好的就是看看这个reference doc .

这里是演示此用法的示例代码。它根据一系列字符在“Hello world”文本周围绘制红色和蓝色线条。

文本位于 JLabel 内部,但您可以在任何组件上调整绘制方法(但您必须调用 graphics.drawChars 来绘制文本。)

(代码不是很好,但是演示了FontMetrics的用法)

package com.example.swing;

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

public class DemoFontMetrics {

public static void main(String[] args){
JFrame frame = new JFrame();
DecoratedLabel label = new DecoratedLabel("hello world !",new int[]{2,4}, new int[]{6,9});
JPanel textContainer = new JPanel(new FlowLayout());
textContainer.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
textContainer.add(label);
frame.getContentPane().add(textContainer);
frame.pack();
frame.setVisible(true);
}

private static class DecoratedLabel extends JLabel{

int startBlue;
int endBlue;
int startRed;
int endRed;

private DecoratedLabel(String text, int[] blueRange, int[] redRange) {
super(text);
startBlue = blueRange[0];
endBlue = blueRange[1];
startRed = redRange[0];
endRed = redRange[1];
}

@Override
public void paint(Graphics g) {
super.paint(g); //draw text

//set line with : 3
Stroke stroke = new BasicStroke(3f);
((Graphics2D)g).setStroke(stroke);

FontMetrics fm = g.getFontMetrics();
int h = fm.getHeight();

//compute blue line coordonate
fm.stringWidth(getText().substring(0,startBlue));
int x1 = fm.stringWidth(getText().substring(0, startBlue));
int x2 = fm.stringWidth(getText().substring(0, endBlue));
g.setColor(Color.BLUE);
g.drawLine(x1,0,x2,0);// draw blue line

//compute red line coordonates
int x3 = fm.stringWidth(getText().substring(0,startRed));
int x4 = fm.stringWidth(getText().substring(0, endRed));
g.setColor(Color.RED);
g.drawLine(x3,h-1,x4,h-1); // draw redline

}
}
}

关于java - 使用java格式化: Mixing text and pictures,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15000537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com