本文共 1993 字,大约阅读时间需要 6 分钟。
是否有方法确定字体对象
真的?
斜体(不是要求斜体字体)?
在我的测试FONT.is italic()、FONT.getStyle()、FONT.getAttributes()中,如果使用FONT.italic样式创建了一个字体对象,那么它都表示该字体对象为斜体。这不考虑是否找到合适的斜体字体。结果是,对于所有意图和目的,字体对象都是斜体,但实际上呈现为纯文本,并且您无法通过编程检查此条件。
这会影响Oracle JDK 11和OpenJDK。
示例代码:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class SimpleFontTest {
private static Font FONT = new Font("Impact", Font.ITALIC, 18);
private static String TEXT = "The Quick Brown Fox";
public static void main(String args[]){
if (args.length > 0 && args[0] != null) {
String fontName = args[0];
FONT = new Font(fontName, Font.ITALIC, 18);
}
// All the different ways that this proves the font is italic
System.out.println("isItalic? " + FONT.isItalic());
System.out.println("style is Font.ITALIC? " + ((FONT.getStyle() & 0b10) == Font.ITALIC));
System.out.println("attributes include POSTURE_OBLIQUE? " + FONT.getAttributes().get(TextAttribute.POSTURE).equals(TextAttribute.POSTURE_OBLIQUE));
JFrame f = new JFrame("Simple Font Test: " + System.getProperty("java.vendor"));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("JLabel: " + TEXT);
label.setFont(FONT);
GraphicsConfiguration gc = f.getGraphicsConfiguration();
BufferedImage image = gc.createCompatibleImage(400, 50);
Graphics2D g = image.createGraphics();
g.setFont(FONT);
g.setColor(Color.BLACK);
g.setBackground(Color.WHITE);
g.clearRect(0, 0, image.getWidth(), image.getHeight());
g.drawString("BufferedImage: " + TEXT, 10, 15);
g.dispose();
JLabel picLabel = new JLabel(new ImageIcon(image));
f.add(label, BorderLayout.PAGE_START);
f.add(picLabel, BorderLayout.CENTER);
f.setSize(400, 200);
f.setVisible(true);
}
}
SYSOUT:
isItalic? true
style is Font.ITALIC? true
attributes include POSTURE_OBLIQUE? true
图形输出:
转载地址:http://qfnzx.baihongyu.com/