Google Tag Manager

2013/08/29

Create 9-slice scaling image JButton

Code

class NineSliceScalingIcon implements Icon {
  private final BufferedImage image;
  private final int a, b, c, d;
  private int width, height;
  public NineSliceScalingIcon(BufferedImage image, int a, int b, int c, int d) {
    this.image = image;
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
  }
  @Override public int getIconWidth() {
    return width;
  }
  @Override public int getIconHeight() {
    return Math.max(image.getHeight(null), height);
  }
  @Override public void paintIcon(Component cmp, Graphics g, int x, int y) {
    Graphics2D g2 = (Graphics2D)g.create();
    g2.setRenderingHint(
        RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    Insets i = ((JComponent)cmp).getBorder().getBorderInsets(cmp);
    //g2.translate(x, y);

    int iw = image.getWidth(cmp);
    int ih = image.getHeight(cmp);
    width  = cmp.getWidth()-i.left-i.right;
    height = cmp.getHeight()-i.top-i.bottom;

    g2.drawImage(image.getSubimage(a, c, iw - a - b, ih - c - d),
                 a, c, width - a - b, height - c - d, cmp);

    if(a > 0 && b > 0 && c > 0 && d > 0) {
      g2.drawImage(image.getSubimage(a, 0, iw - a - b, c),
                   a, 0, width - a - b, c, cmp);
      g2.drawImage(image.getSubimage(a, ih - d, iw - a - b, d),
                   a, height - d, width - a - b, d, cmp);
      g2.drawImage(image.getSubimage(0, c, a, ih - c - d),
                   0, c, a, height - c - d, cmp);
      g2.drawImage(image.getSubimage(iw - b, c, b, ih - c - d),
                   width - b, c, b, height - c - d, cmp);

      g2.drawImage(image.getSubimage(0, 0, a, c), 0, 0, cmp);
      g2.drawImage(image.getSubimage(iw - b, 0, b, c), width - b, 0, cmp);
      g2.drawImage(image.getSubimage(0, ih - d, a, d), 0, height - d, cmp);
      g2.drawImage(image.getSubimage(iw - b, ih - d, b, d), width - b, height - d, cmp);
    }
    g2.dispose();
  }
}

References