【发布时间】:2014-11-16 13:12:13
【问题描述】:
我在 JButton 中使用Font Awesome 来创建可点击图标,但是生成的图标在小尺寸时会出现别名。作为背景知识,Font Awesome 是一个可下载的ttf 文件(字体文件),其中每个字符都是一个“可缩放矢量图标”。在查看了 Google 和堆栈溢出的先前答案后,我尝试通过覆盖 JButton 的 paintComponent 方法来强制抗锯齿;然而,这似乎没有效果:
import java.awt.*;
import java.io.File;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Test extends JFrame{
public Test(){
Font fontAwesome = null;
try {
fontAwesome = Font.createFont(Font.TRUETYPE_FONT, new File("font-awesome-4.2.0\\fonts\\fontawesome-webfont.ttf"));
fontAwesome = fontAwesome.deriveFont(Font.PLAIN, 100);
} catch (FontFormatException | IOException e) {
e.printStackTrace();
}
JButton iconButton = new JButton("\uf0a8"){
@Override
public void paintComponent(Graphics g) {
Graphics2D graphics2d = (Graphics2D) g;
graphics2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//graphics2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//graphics2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
//graphics2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
super.paintComponent(graphics2d);
}
};
iconButton.setFont(fontAwesome);
iconButton.setFocusPainted(false);
this.add(iconButton);
this.setVisible(true);
this.pack();
}
public static void main(String[] args){
new Test();
}
}
下图显示了字体大小为 30、100 和 200 的字体图标:
如何为小字体强制消除锯齿?
更新:我使用内置 java 字体而不是 Font Awesome 测试了相同的代码,并且完全相同的问题适用。
【问题讨论】:
-
您可以尝试缩放
BufferedImage,如JDigit所示。
标签: java swing fonts jbutton font-awesome