package com.sap.dbmtk.demo.utils;

import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.ImageIcon;
import javax.swing.JLabel;

public class ImageLabel extends JLabel
{
	private static final long serialVersionUID = 1L;
	private Dimension _boundary = null;

	public ImageLabel(ImageIcon icon, Dimension boundary)
	{
		super(icon);
		_boundary = boundary;
	}

	@Override
	public void paintComponent(Graphics g)
	{
		super.paintComponent(g);
		
		// First fill the area with the background color.
		g.setColor(getBackground());
//		g.setColor(Color.BLUE);
		g.fillRect(0, 0, getWidth(), getHeight());

		ImageIcon imageIcon = (ImageIcon)getIcon();
		
		// Get newSize of the image that "fits" within the boundaries, but keep the image aspect ratio
		Dimension imgSize  = new Dimension(imageIcon.getIconWidth(), imageIcon.getIconHeight());
		Dimension newSize  = SwingUtils.getScaledDimension(imgSize, _boundary);

		int width  = (int) newSize.getWidth(); 
		int height = (int) newSize.getHeight();
		int x = 0;
		int y = 0;

		// Calculate x,y offset to center the image in the current drawing area
		if ( width < getWidth() )
			x = (int) (getWidth() - newSize.getWidth()) / 2;

		if ( height < getHeight() )
			y = (int) (getHeight() - newSize.getHeight()) / 2;
		
		// Draw the image
		g.drawImage( imageIcon.getImage(), x, y, width, height, this);
	}
}
