In
this example we are going to see how to draw an image with Antialiasing
enabled. The notion of antialiasing is one of the most famous among the
graphics world. This will help you to make sharper graphics and make
your images look very clear and avoid pixelation.
In short, in order to enable antialiasing in your drawing, you should:
- Use
Graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
to turn antialiasin on. - Use
Graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
to turn antialiasing off.
Let’s see the code snippet that follows:
001 | package com.javacodegeeks.snippets.desktop; |
003 | import java.awt.Component; |
005 | import java.awt.FontMetrics; |
006 | import java.awt.Frame; |
007 | import java.awt.Graphics; |
008 | import java.awt.Graphics2D; |
009 | import java.awt.RenderingHints; |
011 | public class AntialiasingDrawing { |
013 | public static void main(String[] args) { |
017 | Frame frame = new Frame(); |
021 | frame.add( new CustomPaintComponent()); |
027 | int frameHeight = 300 ; |
029 | frame.setSize(frameWidth, frameHeight); |
031 | frame.setVisible( true ); |
036 | * To draw on the screen, it is first necessary to subclass a Component |
037 | * and override its paint() method. The paint() method is automatically called |
038 | * by the windowing system whenever component's area needs to be repainted. |
040 | static class CustomPaintComponent extends Component { |
042 | public void paint(Graphics g) { |
046 | Graphics2D g2d = (Graphics2D)g; |
049 | * The coordinate system of a graphics context is such that the |
050 | * origin is at the northwest corner and x-axis increases toward the |
051 | * right while the y-axis increases toward the bottom |
058 | int width = getSize().width- 1 ; |
060 | int height = getSize().height- 1 ; |
064 | g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); |
068 | g2d.drawOval(width/ 8 ,height/ 8 , 3 *width/ 4 , 3 *height/ 4 ); |
072 | g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); |
076 | g2d.drawOval(width/ 4 , height/ 4 , width/ 2 , height/ 2 ); |
080 | g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); |
084 | Font font = new Font( "Serif" , Font.PLAIN, 12 ); |
088 | FontMetrics fontMetrics = g2d.getFontMetrics(); |
092 | g2d.drawString( "Antialiazing is ON" , x, y+fontMetrics.getAscent()); |
096 | g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); |
100 | g2d.drawString( "Antialiazing is OFF" , x, y+ 2 *fontMetrics.getAscent()); |
This was ane example on how to draw using Antialiasing.