Assuming you actually want smooth (non-aliased) text, TextLayout
may make this easier. The FontRenderContext
constructor can manage the anti-aliasing and fractional metrics settings.
Addendum: Using g2d.setColor(Color.blue)
seems to produce the expected effect.
Addendum: On Mac OS X, the Pixie
application in /Developer/Applications/Graphics Tools/
is convenient for examining the anti-alias pixels. On other platforms, Zoom
may be used.
/** @see https://stackoverflow.com/questions/4285464 */
public class BITest extends JPanel {
private BufferedImage image = createNameOnButton("Sample");
public BITest() {
this.setPreferredSize(new Dimension(
image.getWidth(), image.getHeight()));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
public BufferedImage createNameOnButton(String label) {
Font font = new Font("Arial", Font.PLAIN, 64);
FontRenderContext frc = new FontRenderContext(null, true, true);
TextLayout layout = new TextLayout(label, font, frc);
Rectangle r = layout.getPixelBounds(null, 0, 0);
System.out.println(r);
BufferedImage bi = new BufferedImage(
r.width + 1, r.height + 1,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) bi.getGraphics();
g2d.setColor(Color.blue);
layout.draw(g2d, 0, -r.y);
g2d.dispose();
return bi;
}
private void display() {
JFrame f = new JFrame("BITest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setUndecorated(true);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new BITest().display();
}
});
}
}