gpt4 book ai didi

java - 除了删除线之外,AttributedString 的任何功能都不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 09:45:46 25 4
gpt4 key购买 nike

我必须将一个字符串写入BufferedImage。我正在使用 AttributedStringTextAttribute.STRIKETHROUGH 正在工作。上标、下标等都不起作用。

public class TextAttributesSuperscript  {

static String Background = "input.png";
static int curX = 10;
static int curY = 50;

public static void main(String[] args) throws Exception {
AttributedString attributedString= new AttributedString("this is data. this data should be super script");

attributedString.addAttribute(TextAttribute.FONT, new Font("TimesRoman", Font.PLAIN, 18));
attributedString.addAttribute(TextAttribute.FOREGROUND, Color.BLACK);


attributedString.addAttribute(TextAttribute.FONT, new Font("TimesRoman", Font.BOLD, 18), 30,33);
attributedString.addAttribute(TextAttribute.FOREGROUND, Color.BLUE, 29,33);
attributedString.addAttribute(TextAttribute.SUPERSCRIPT,TextAttribute.SUPERSCRIPT_SUPER,30,33);

final BufferedImage image = ImageIO.read(new File(Background));
Graphics g = image.getGraphics();
g.drawString(attributedString.getIterator(), curX, curY);
g.dispose();
ImageIO.write(image, "png", new File("output.png"));
}
}

执行上面的代码时。上标部分不起作用(文本没有像上标一样打印)

最佳答案

我不太确定为什么你的代码不起作用,因为这样做似乎完全符合逻辑。我不明白为什么有些属性有效而有些无效。

但是根据the Java 2D Tutorial: Using Text Attributes to Style TextSUPERSCRIPT属性应该在字体上设置,而不是在文本本身上设置。 IE。使用Font.deriveFont(Map<Attribute, ?> attributes) .

以下内容对我有用(我稍微修改了您的代码以不依赖于您的后台文件):

public class TextAttributesSuperscript  {

static int curX = 10;
static int curY = 50;

public static void main(String[] args) throws Exception {
AttributedString attributedString = new AttributedString("this is data. this data should be super script");

attributedString.addAttribute(TextAttribute.FONT, new Font("TimesRoman", Font.PLAIN, 18));
attributedString.addAttribute(TextAttribute.FOREGROUND, Color.BLACK);

Font superScript = new Font("TimesRoman", Font.BOLD, 18)
.deriveFont(Collections.singletonMap(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER));
attributedString.addAttribute(TextAttribute.FONT, superScript, 30, 33);
attributedString.addAttribute(TextAttribute.FOREGROUND, Color.BLUE, 30,33);

BufferedImage image = new BufferedImage(400, 100, BufferedImage.TYPE_INT_ARGB);

Graphics2D g = image.createGraphics();
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
g.setColor(Color.WHITE);

g.fillRect(0, 0, image.getWidth(), image.getHeight());
g.drawString(attributedString.getIterator(), curX, curY);
g.dispose();

ImageIO.write(image, "png", new File("output.png"));
}
}

关于java - 除了删除线之外,AttributedString 的任何功能都不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55445016/

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