Posted by Darryl Burke on April 8, 2012
When writing about StretchIcon, published earlier, I mentioned that the image chosen for a StretchIcon should be large enough that it does not get magnified in fitting it to the component, since drawing an image larger than its natural size can lead to pixelation. ShrinkIcon extends StretchIcon to ensure such pixelation doesn’t happen.
Like StretchIcon, ShrinkIcon is meant to be used only in conjunction with a component whose size is determined by the size and layout of the container in which it is placed. The image will be reduced if necessary to fit within the bounds of the component; it will not, however, be drawn at larger than its natural size.
In the event that the component is wider and/or taller than the image, ShrinkIcon will pad and center the image horizontally and/or vertically. Only when the component is too small to accommodate the image at its natural size will the image be scaled on one or both axes to fit, optionally maintaining the aspect ratio of the image. This can make it a better choice than StretchIcon for displaying images of varied sizes in components that are all the same size; for example, JLabels in a GridLayout. While large images will be reduced to fit, smaller images aren’t at the risk of being blown up and pixelated beyond recognition.
Like StretchIcon, ShrinkIcon is a drop-in replacement for ImageIcon, except, again, that ImageIcon’s no-arg constructor isn’t supported.