I want to display a preview image which is a resized version of the original image with aspect ratio preserved in a fixed size Label. For example, I have an image of 1024x786 and I want to display it in a Label which has size 500x500. I want it to fit in this label keeping the aspect ratio of the image intact.
It would also be nice if the image could be automatically resized when a user resizes the part.
Is it possible to do this with Label? or do I need a canvas for this?
This image scaling code is based on JFace ImageDescriptor
:
ImageDescriptor scaleImage(Display display, ImageDescriptor imageDesc,
int maxWidth, int maxHeight)
{
if (imageDesc == null)
return null;
ImageData imageData = imageDesc.getImageData();
if (imageData == null) // Can by JPEG using CMYK colour space etc.
return imageDesc;
int newHeight = maxHeight;
int newWidth = (imageData.width * newHeight) / imageData.height;
if (newWidth > maxWidth)
{
newWidth = maxWidth;
newHeight = (imageData.height * newWidth) / imageData.width;
}
// Use GC.drawImage to scale which gives better result on Mac
Image newImage = new Image(display, newWidth, newHeight);
GC gc = new GC(newImage);
Image oldImage = imageDesc.createImage();
gc.drawImage(oldImage, 0, 0, imageData.width, imageData.height, 0, 0, newWidth, newHeight);
ImageDescriptor result = ImageDescriptor.createFromImage(newImage);
oldImage.dispose();
gc.dispose();
return result;
}