Rough and smooth lines
When drawing on a JPanel
, I can set anti-aliasing on as a rendering hint and then draw a line that has smoothed edges.
If, however, I create a BufferedImage
and draw the same line on it with anti-aliasing, and then I use JPanel.drawImage
to draw the buffered image, the line is drown roughly (e.g. anti-aliasing=off).
I can't determine how to draw a line on a buffered image with anti-aliasing. Can someone clarify how this is done?
In the below example, I'm simply creating two JFrame
. In one frame I create a panel and draw on it directly. In the other frame I create a panel, then a buffered image that I draw on, then use JPanel.drawImage
to display. I want the line shown in the buffered image to be drawn with anti-aliasing.
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args){
doDirect();
doBuffered();
}
public static void doBuffered(){
JFrame frame = new JFrame();
frame.setTitle("BufferedImage drawn with antialiasing on");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel canvas = new JPanel(){
@Override
protected void paintComponent(Graphics g){
BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
Graphics2D ig2d = image.createGraphics();
ig2d.setColor(Color.BLACK);
ig2d.setStroke(new BasicStroke(3));
ig2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
ig2d.drawLine(10, 10, 70, 90);
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(image, 0, 0, null);
}
};
canvas.setPreferredSize(new Dimension(100, 100));
frame.getContentPane().add(canvas, BorderLayout.CENTER);
frame.setEnabled(true);
frame.pack();
frame.setVisible(true);
}
public static void doDirect(){
JFrame frame = new JFrame();
frame.setTitle("Directly drawn with antialiasing on");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel canvas = new JPanel(){
@Override
protected void paintComponent(Graphics g){
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.BLACK);
g2d.setStroke(new BasicStroke(3));
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.drawLine(10, 10, 70, 90);
}
};
canvas.setPreferredSize(new Dimension(100, 100));
frame.getContentPane().add(canvas, BorderLayout.CENTER);
frame.setEnabled(true);
frame.pack();
frame.setVisible(true);
}
}
I ran your sample and both methods of drawing seemed to apply the antialiasing. It may be a bug in the version of the jdk you're using. I'm running on Windows with jdk 1.8.0_77 and also tried with jdk 1.7.0_79.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With