Swing Pixel Stretch / Distortion
I have been trying to render a very small font (5 pixel per 5 pixel) on a JPanel for a personal project where the graphics are composed mainly of text. But as soon as I rendered a ton of dots and #
's for debugging purpose, I ran into a bug. That bug was at the time ignored, but now that I am trying to polish the system, its really becoming a nuisance and can't find anything that helps online.
The Bug
The 5x5 images are scaled up and down almost randomly, making the graphics horrible. [(see here)][1]
The lines of the #
's aren't regular, nor the dots sizes.
Expected Behaviour
The lines should be regular , and the dots should be evenly sized.
What I tried.
I toggled on and off antialiasing ( RenderingHints
), to no avail.
My font (that was made using a great website, [this][2]), has been set to a letter spacing of 5px, and has been exported to ttf. Im drawing it on a BufferedImage
at 5x5 pixel size, then upscaling the BufferedImage
to twice its size for visibility.
I had this problem before on another project I did with a friend, yet they didn't have it on their computer while mine was still bugging.
The Code
I'm registering the font as so:
InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream("FontName.ttf");
font1= Font.createFont(Font.TRUETYPE_FONT, stream).deriveFont(5f);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font1);
I then draw pieces using the following method:
g.drawString(s.substring(i,i+1),x*FONT_WIDTH+i*FONT_WIDTH,y*FONT_HEIGHT+FONT_HEIGHT);
(All the variables are at their good values).
I change the RenderingHints
the following way:
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_OFF);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
I turned off antialiasing because I felt like it could do that kind of thing.
Conclusion
I hope someone would provide me with either a way to fix my bug or a path I could follow to fix it.
Edit
Added System.setProperty("sun.java2d.uiScale", "1");
from sorifiend's link, fixed the scaling issues.
Edit 2: There still are some bugs, but they are drastically reduced.
[1]: https://i.stack.imgur.com/QApbU.png
[2]: http://www.pentacom.jp/pentacom/bitfontmaker2/#