How do I display an ImageIcon from an image file in the high-resolution of today's screens?

8 hours ago 1
ARTICLE AD BOX

I'm trying to read an icon from a .png file and display it at half size, to take advantage of the higher resolution of today's screens. But nothing I'm trying works.

Here's what I've tried:

In the image below, to create "32 scaled to 16," I called imageIcon.getImage().getScaledInstance(16, 16, Image.SCALE_SMOOTH) This method was written long before high-res screens were invented, and returns a low-res image at half size.

To create "16-pixel variant," I created a MultiResolutionImage with 16-pixel and 32 pixel variants, and called multiResImage.getResolutionVariant(16, 16) which asks for the 16 pixel variant, hoping it would scale the 32 pixel variant down. It did use the 32-pixel variant, but at full size. This makes me wonder what that class is good for.

To create "Half Size Button," I created a half-size subclass of ImageIcon, and overrode the three methods used to draw the image. It partly worked. This was the only solution that drew the image at the correct size and resolution, but it put the image in the wrong place. (The code for this class is below.)

So none of these worked. You can download the code at https://github.com/SwingGuy1024/IconFamilyBug and try this yourself. Here's what it drew:

Image of results of everything I've tried.

Here's the half-size ImageIcon class:

public static class HalfSizeIcon extends ImageIcon { private static final float scale = 0.5f; public HalfSizeIcon(ImageIcon icon) { super(icon.getImage()); if (icon.getDescription() != null) { setDescription(icon.getDescription()); } } @Override public synchronized void paintIcon( final Component c, final Graphics g, final int x, final int y) { Graphics2D g2 = (Graphics2D) g; AffineTransform savedTransform = g2.getTransform(); g2.scale(scale, scale); super.paintIcon(c, g2, x, y); g2.setTransform(savedTransform); } @Override public int getIconWidth() { return Math.round(scale * (super.getIconWidth())); } @Override public int getIconHeight() { return Math.round(scale * (super.getIconHeight())); } }
Read Entire Article