【发布时间】:2011-11-03 09:00:00
【问题描述】:
我想渲染一个 Java Swing 组件,例如一个 JButton,我也把它放在一个 JFrame 上,到一个 BufferedImage。这通常有效,但有一个主要缺点:文本抗锯齿,尤其是“LCD”抗锯齿模式,在渲染到 BufferedImage 时不起作用。
我已经把一些示例代码放在一起来演示这个问题,但首先是我的系统信息:
- 操作系统: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 之间的区别:
实际上图像中有一些文本抗锯齿,但不是 JFrame 屏幕上显示的 LCD 优化的抗锯齿(默认 LookAndFeel 也会出现此问题,而不仅仅是“WindowsLookAndFeel”)。
我已经尝试为“g2d”上的文本抗锯齿显式设置 RenderingHint,BufferedImage 的 Graphics2D 上下文如下所示:
g2d.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB );
但是一点效果都没有。
我迫切需要将 JButton 渲染为图像文件,就像它在屏幕上渲染一样(这只是一个示例,实际上我需要渲染一些更复杂的组件,它们都存在抗锯齿问题),我希望有是一个真正的解决方案,没有任何讨厌的解决方法,例如截屏或其他东西。
非常感谢任何帮助 - 非常感谢!
【问题讨论】:
-
为什么不发布SSCCE?
UIManager.setLookAndFeel( "com.sun.java.swing.plaf.windows.WindowsLookAndFeel" );,尤其是可以在 Mac 上测试的。或 *nix。 -
感谢您的评论 - 除了 windows 的外观和感觉之外,还有什么其他东西使我的示例不是 SSCCE?我很乐意发布一个可在 Mac 或 *nix 下测试的示例,但我不明白为什么(除了外观和感觉)它不应该在这些操作系统上运行?
-
我注意到的第一件事是缺少导入。
-
您的问题得到解答了吗?
标签: java bufferedimage java-2d antialiasing graphics2d