I am new to Java and trying to use Java2D Graphics to create a Image. But the output is coming as anti-aliased. I tried many ways to rectify it but doesn't work. The characters are getting distorted or jagged.
public BufferedImage createNameOnButton(String label) {
int messageWidth = 0;
Font font = new Font("Arial", Font.PLAIN, 11);
BufferedImage bi = new BufferedImage(
10, 10, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D) bi.getGraphics();
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2d.setRenderingHint(
RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2d.setFont(font);
bi = g2d.getDeviceConfiguration()
.createCompatibleImage(500, 30, Transparency.BITMASK);
FontMetrics fm = bi.getGraphics().getFontMetrics(font);
int messageHeight = fm.getHeight() - fm.getDescent();
for (char ch : label.toCharArray()) {
messageWidth += fm.charWidth(ch);
}
bi = bi.getSubimage(50, 0, messageWidth + 10, fm.getHeight());
Graphics g = bi.getGraphics();
g.setColor(Color.black);
AttributedString as = new AttributedString(label);
as.addAttribute(TextAttribute.FONT, font);
g.drawString(as.getIterator(), 5, messageHeight);
g2d.dispose();
g.dispose();
return bi;
}
Can anyone please help me to rectify the error?
Assuming you actually want smooth (non-aliased) text,
TextLayout
may make this easier. TheFontRenderContext
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.I found that just this line does the trick:
After that, just use drawString().
As Traroth mentioned it is more than likely due to
Instead this should be