Java Swing Icon getScaledIcon(Icon icon)

Here you can find the source of getScaledIcon(Icon icon)

Description

Get a scaled icon starting from an icon.

License

Apache License

Parameter

Parameter Description
icon a parameter

Declaration

public static ImageIcon getScaledIcon(Icon icon) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.awt.BasicStroke;

import java.awt.Graphics2D;

import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.swing.Icon;
import javax.swing.ImageIcon;

public class Main {
    /**//from   w  w w . java  2 s.c  o  m
     * Get a scaled icon starting from an icon. The rescaling is performed with
     * the specified integer scale. This is done through a buffered image.
     *
     * @param icon
     * @return
     */
    public static ImageIcon getScaledIcon(Icon icon) {
        // get icon  size
        int iconWidth = icon.getIconWidth();
        int iconHeight = icon.getIconHeight();
        // get the scaled sizes
        int scale = 2;
        int scaledIconWidth = iconWidth / scale;
        int scaledIconHeight = iconHeight / scale;
        // create the buffered image - 8-bit RGBA color components packed into integer pixels
        BufferedImage bufferedImage = new BufferedImage(scaledIconWidth, scaledIconHeight,
                BufferedImage.TYPE_INT_ARGB);
        // create graphics from the image and scale it
        Graphics2D graphics2D = bufferedImage.createGraphics();
        setGraphics(graphics2D);
        graphics2D.scale(0.5, 0.5);
        // draw the icon
        icon.paintIcon(null, graphics2D, 0, 0);
        // dispose of the graphics
        graphics2D.dispose();
        // create the actual image icon
        return new ImageIcon(bufferedImage);
    }

    /**
     * set graphics: implementing rendering process for a Graphics2D object
     *
     * @param g2d
     */
    public static void setGraphics(Graphics2D g2d) {
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        BasicStroke stroke = new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
        g2d.setStroke(stroke);
    }
}

Related

  1. getIconFromExtension(String f, boolean folder)
  2. getIconInterTrial()
  3. getIcono()
  4. getPressedExitIcon(int x, int y)
  5. getResourceIcon(Object target, String name)
  6. getScaledIcon(Icon tmpIcon, int w, int h, boolean incr)
  7. getScaledIcon(String resourceName, int width, int height)
  8. getSize(String graphIconPath)
  9. getTransparentIcon(int width)