I am trying to clip my Graphics2D
canvas using RoundRectangle2D.Double
, but the clipping is very jagged and not smooth. I have the following code to anti-alias:
Graphics2D g = (Graphics2D)graphics;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
I know it is working because when I draw a RoundRectangle2D.Double
using Graphics2D.fill()
the smoothing is fine. How do I make the clipping smooth?
Note: I am aware of this post, but this pertains to JPanels
and images, but I am not dealing with either of those. I am just trying to smoothly clip a section of the drawing area.
Thanks in advance for any help.
Example.java
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import javax.swing.*;
public class Example extends JPanel {
public Example() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocation(10, 10);
setPreferredSize(new Dimension(400, 400));
setBackground(Color.BLACK);
Container container = frame.getContentPane();
container.add(this);
frame.pack();
frame.setVisible(true);
}
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
Graphics2D g = (Graphics2D)graphics;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
RoundRectangle2D clippingArea = new RoundRectangle2D.Double(50, 50, getWidth() - 100, getHeight() -100, 40, 40);
g.setClip(clippingArea);
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.BLACK);
String s = "area for me to draw on where";
g.drawString(s, getWidth()/2 - g.getFontMetrics().stringWidth(s)/2, getHeight()/2 - g.getFontMetrics().getHeight());
s = "the roundrectangle should be anti-aliased";
g.drawString(s, getWidth()/2 - g.getFontMetrics().stringWidth(s)/2, getHeight()/2);
}
public static void main(String[] args) {
new Example();
}
}