我必须给BufferedImage
写一个字符串。我正在使用AtrributedString
。 TextAttribute.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 Text,SUPERSCRIPT
属性应该设置在字体上,而不是文本本身。 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"));
}
}