是否可以使用“SansSerif”等逻辑字体在同一Java应用程序中绘制繁体和简体中文字符?我只使用CJK代码点获得传统的变种。
我在创建字体之前尝试过设置Locale.setDefault()和GraphicsEnvironment.preferLocaleFonts()。我在启动java.exe时尝试在命令行上使用-Duser.language和-Duser.country。还尝试使用设置的AttributedCharacterIterator.Attribute.LANGUAGE创建字体。没效果。
我没有使用Swing或AWT。只是试图绘制一个屏幕外的BufferedImage。我在Windows 7上,我验证我安装了支持繁体和简体中文(MingLiU和SimSun)的字体。我还检查了Java的字体配置文件,我看到那里列出了这两种字体。
我还应该做什么?
答案 0 :(得分:0)
是的,您可以用Java显示简体中文和繁体中文文本,只要您的字体包含两组字符。
我写了这个简短的程序来演示:
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
public class ChineseFonts {
public static final int GAP = 35;
public static final int FONTS_PER_LINE = 2;
public ChineseFonts(String s) {
Rectangle rect = new Rectangle(0, 0, 1024, 768);
BufferedImage bufferedImage = new BufferedImage((int) Math.ceil(rect.getWidth()), (int) Math.ceil(rect.getHeight()), BufferedImage.TYPE_4BYTE_ABGR);
Graphics graphics = bufferedImage.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(rect.x, rect.y, rect.width, rect.height);
graphics.setColor(Color.BLUE);
String title = "Chinese Fonts on " + System.getProperty("os.name") + ", version " + System.getProperty("os.version");
int fontY = 30;
printString(title, graphics, 0, fontY, new Font(Font.SERIF, Font.BOLD | Font.ITALIC, 28), false);
fontY += GAP + 10;
int counter = 0;
for (String fontName : new String[]{Font.MONOSPACED, Font.SANS_SERIF, Font.SERIF}) {
Font font = new Font(fontName, Font.PLAIN, 24);
printString(s, graphics, counter++, fontY, font, true);
if (counter % FONTS_PER_LINE == 0)
fontY += GAP;
}
Font[] localFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
List<Font> chineseFonts = new ArrayList<Font>();
String simplifiedAndTraditionalChinese = "????";
for (int j = 0; j < localFonts.length; j++) {
if (localFonts[j].canDisplayUpTo(simplifiedAndTraditionalChinese) == -1) {
chineseFonts.add(localFonts[j].deriveFont(24F));
}
}
for (Font font : chineseFonts) {
printString(s, graphics, counter++, fontY, font, true);
if (counter % FONTS_PER_LINE == 0)
fontY += GAP;
}
graphics.dispose();
try {
ImageIO.write(bufferedImage, "png", new File("chineseFonts.png"));
} catch (Exception e) {
// ignored
}
}
private void printString(String s, Graphics graphics, int counter, int y, Font font, boolean showFontDetails) {
graphics.setFont(font);
if (showFontDetails)
s = font.getFamily() + " " + s;
graphics.drawString(s, 20 + (counter % FONTS_PER_LINE) * 510, y);
if (showFontDetails)
System.out.println("Printing " + s + " using " + font.getName() + ", which is " + font.getFontName() + " in family " + font.getFamily());
}
public static void main(String args[]) {
new ChineseFonts("S: 漢字 T: 汉字");
}
}
使用的2个简体中文和2个繁体中文字符来自维基百科上的汉字页面。运行时,所有使用的字体都打印到stdout,图像以字体名称和中文字符输出。
以下是3种逻辑字体和第一种有效的物理字体: