Search code examples
javagraphicspaintgraphics2d

fixing blurrieness with Graphics2D in JAVA


I was wondering why displaying text in my frame has to be so blury, and i came across this piece of code, which is working by the way

public void paint(Graphics graphicsObject){
    if(graphicsObject instanceof Graphics2D){
        Graphics2D g2D = (Graphics2D) graphicsObject;       
        g2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    }
    graphicsObject.drawString("not blurry text display", 200, 200);
}

having dificulties trying to understand how this work out.

  • how come g2D.setRenderingHint is fixing my blurry problem, but i dont use it to paint my string?

Solution

  • First, what this fixed was not blurring. It was aliasing.

    Aliasing occurs when drawing functions try to create curvy shapes using a raster image - a matrix of pixels, which are squares. If the lines are not vertical or horizontal, you end up with "stairs" - edges that are jaggy.

    Antialiasing is a way to make this effect less visible to the eye, by using additional pixels around the drawn line, which are painted in different tones between the foreground and the background. This cheats our eyes to see the line as "smooth". If you zoom an image drawn with antialiasing, you may notice those pixels around the actual line.

    So, actually, antialiasing blurs the line, and this makes it seem smoother to our eyes.


    As to your actual question - you are using the graphics object to draw the line. You set the hint in the graphics object by accessing the object in its form as a Graphics2D. Even though you then go on and use the graphicsObject using its regular Graphics reference, the method drawString() is overridden. This means that it will be activated in the concrete object that implements it, which sees - and uses - the RenderingHint hash map where your hint is stored.