Display an Image Scaled to Maintain Its Proportions 

This is a very simple example of how to display and image using GDI+. The matrix transformation method call changes the image size and position if the screen size has changed.

// Create the image
CComBSTR bstrImage(m_strName.c_str());
Bitmap bmpImage(bstrImage, FALSE);

// Determine whether any scaling is required
Matrix* pScaleMatrix = new Matrix();
this->ScaleImage(hWnd, &pScaleMatrix);
pCanvas->SetTransform(pScaleMatrix);

// Draw the image at the specified position
pCanvas->SetSmoothingMode(SmoothingModeHighQuality);
pCanvas->DrawImage(&bmpImage, m_lXPos, m_lYPos, m_lWidth, m_lHeight);

// Reset the world transformation matrix
pCanvas->ResetTransform();

// Clean up resources
if(pScaleMatrix != 0)
{
 delete pScaleMatrix;
 pScaleMatrix = 0;
}

bstrImage.Empty();

The code which is used to calculate the scaling matrix (ScaleImage function above) looks like this:

if(::GetClientRect(hWnd, &rctClientArea))
{
// Determine the width and height of the window
rWidth = (rctClientArea.right - rctClientArea.left);
rHeight = (rctClientArea.bottom - rctClientArea.top);

// Calculate X scale factor
if(abs(rWidth - m_lPageWidth) > rDelta)
{
 rXScale = rWidth / m_lPageWidth;
}

// Calculate Y scale factor
if(abs(rHeight - m_lPageHeight) > rDelta)
{
 rYScale = rHeight / m_lPageHeight;
}

// Update scaling matrix
(*ScaleFactor)->Scale(rXScale, rYScale);
}

The variables in the above code block are declared as follows:

REAL rWidth = 0.0;
REAL rHeight = 0.0;
REAL rXScale = 1.0;
REAL rYScale = 1.0;
REAL rDelta = 0.0001;