裁剪和調整 GDI+ 影像

Graphics類別提供數個DrawImage方法,其中有些方法具有可用來裁剪和縮放影像的來源和目的地矩形參數。

下列範例會從檔案Apple.gif建構 Image 物件。 程式碼會以原始大小繪製整個 Apple 影像。 然後,程式碼會呼叫Graphics物件的DrawImage方法,在大於原始 Apple 影像的目的地矩形中繪製一部分的 apple 影像。

DrawImage方法會藉由查看來源矩形來判斷要繪製的 Apple 部分,該矩形是由第三個、第四個、第五個和第六個引數所指定。 在此情況下,Apple 會裁剪成其寬度的 75%,高度為 75%。

DrawImage方法會決定繪製裁剪的 Apple 的位置,以及查看第二個引數所指定的目的地矩形,讓裁剪的 Apple 變得大到多大。 在此情況下,目的地矩形的寬度為 30%,且比原始影像高 30%。

Image image(L"Apple.gif");
UINT width = image.GetWidth();
UINT height = image.GetHeight();
// Make the destination rectangle 30 percent wider and
// 30 percent taller than the original image.
// Put the upper-left corner of the destination
// rectangle at (150, 20).
Rect destinationRect(150, 20, 1.3 * width, 1.3 * height);
// Draw the image unaltered with its upper-left corner at (0, 0).
graphics.DrawImage(&image, 0, 0);
// Draw a portion of the image. Scale that portion of the image
// so that it fills the destination rectangle.
graphics.DrawImage(
   &image,
   destinationRect,
   0, 0,              // upper-left corner of source rectangle
   0.75 * width,      // width of source rectangle
   0.75 * height,     // height of source rectangle
   UnitPixel);

下圖顯示原始 apple 和已縮放、裁剪的 apple。

顯示 Apple 的圖例,然後是原始 Apple 的放大部分