共用方式為


關於裁剪和縮放 GDI+ 影像

您可以使用 Graphics 類別的 DrawImage 方法來繪製和放置影像。 DrawImage 是多載的方法,因此有數種方式可讓您提供自變數。 Graphics::DrawImage 方法的其中一個變化會接收 Image 物件的位址,以及 Rect 物件的參考。 矩形會指定繪圖作業的目的地;也就是說,它會指定要繪製影像的矩形。 如果目的矩形的大小與原始影像的大小不同,則會縮放影像以符合目的矩形。 下列範例將相同的影像繪製三次:一次以原尺寸,一次進行擴展,一次進行壓縮。

Bitmap myBitmap(L"Spiral.png");
Rect expansionRect(80, 10, 2 * myBitmap.GetWidth(), myBitmap.GetHeight());
Rect compressionRect(210, 10, myBitmap.GetWidth() / 2, 
   myBitmap.GetHeight() / 2);

myGraphics.DrawImage(&myBitmap, 10, 10);
myGraphics.DrawImage(&myBitmap, expansionRect);
myGraphics.DrawImage(&myBitmap, compressionRect);

上述程式代碼以及特定檔案 Spiral.png會產生下列輸出。

插圖顯示三個影像版本的 :一般、拉寬和縮小為原始大小的一半

Graphics::DrawImage 方法的某些變體具有源矩形參數和目標矩形參數。 來源矩形會指定要繪製的原始影像部分。 目的矩形會指定要繪製影像部分的位置。 如果目的矩形的大小與來源矩形的大小不同,則會縮放影像以符合目的矩形。

下列範例會從 檔案 Runner.jpg建構 Bitmap 物件。 繪製整個影像時沒有縮放比例(0,0)。 然後將影像的一小部分繪製兩次:一次縮小,一次放大。

Bitmap myBitmap(L"Runner.jpg"); 

// The rectangle (in myBitmap) with upper-left corner (80, 70), 
// width 80, and height 45, encloses one of the runner's hands.

// Small destination rectangle for compressed hand.
Rect destRect1(200, 10, 20, 16);

// Large destination rectangle for expanded hand.
Rect destRect2(200, 40, 200, 160);

// Draw the original image at (0, 0).
myGraphics.DrawImage(&myBitmap, 0, 0);

// Draw the compressed hand.
myGraphics.DrawImage(
   &myBitmap, destRect1, 80, 70, 80, 45, UnitPixel);

// Draw the expanded hand. 
myGraphics.DrawImage(
   &myBitmap, destRect2, 80, 70, 80, 45, UnitPixel);

下圖顯示未調整的影像,以及壓縮和展開的影像部分。

顯示影像的螢幕快照,接著壓縮影像的一部分,然後再將相同部分展開