我想把一个Java Swing组件(如JButton),同时放在JFrame上,渲染成BufferedImage。这个一般都没有问题,但有一个主要的缺陷:当渲染到BufferedImage时,文本反锯齿,特别是“LCD”反锯齿模式不起作用。
我写了一些示例代码来演示这个问题,首先是我的系统信息:
- 操作系统:Windows 7 64位
- JVM:1.6.0_26-b03(32位)
以下示例代码将创建一个简单的JFrame,在上面放置一个JButton,并将JButton渲染到文件“test.png”中:
public class TextAntiAliasingTest
{
public TextAntiAliasingTest() throws IOException
{
// Create Test-Button which will be rendered to an image
JButton button = new JButton( "The Test-Button" );
button.setSize( 200, 70 );
button.setLocation( 200, 150 );
// Create JFrame
final JFrame frame = new JFrame();
frame.setSize( 800, 600 );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setLayout( null );
frame.setLocationRelativeTo( null );
frame.add( button );
// Show JFrame
SwingUtilities.invokeLater( new Runnable() {
@Override public void run() {
frame.setVisible( true );
}
});
// Render JButton to an BufferedImage
BufferedImage image = new BufferedImage( 800, 600, BufferedImage.TYPE_INT_ARGB );
Graphics2D g2d = (Graphics2D)image.getGraphics();
button.paint( g2d );
// Write BufferedImage to a PNG file
ImageIO.write( image, "PNG", new File( "test.png" ) );
}
public static void main( String[] args ) throws Exception
{
UIManager.setLookAndFeel( "com.sun.java.swing.plaf.windows.WindowsLookAndFeel" );
System.setProperty( "awt.useSystemAAFontSettings", "lcd" );
new TextAntiAliasingTest();
}
}
以下图片显示了JFrame中的JButton和图像文件中渲染的相同JButton之间的差异:
![enter image description here](https://istack.dev59.com/piq96.webp)
我已经尝试明确设置"g2d"的文本抗锯齿的RenderingHint,即BufferedImage的Graphics2D上下文,如下所示:
g2d.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB );
但这完全没有效果。
我急需将JButton渲染成屏幕上显示的图像文件(这只是一个示例,实际上我需要渲染一些更复杂的组件,它们都遭受了抗锯齿问题),我希望有一个真正的解决方案,而不是采取什么可怕的变通方法,比如截屏。
非常感谢任何帮助-非常感谢!
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
特别是那些可以在Mac或*nix上进行测试的。 - Andrew Thompson