如何:裁剪和縮放影像

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

範例

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

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

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

下圖顯示原始的蘋果和縮放、裁剪的蘋果。

Screenshot of an original image and the same image cropped.

Image image = new Bitmap("Apple.gif");

// Draw the image unaltered with its upper-left corner at (0, 0).
e.Graphics.DrawImage(image, 0, 0);

// 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).
int width = image.Width;
int height = image.Height;
RectangleF destinationRect = new RectangleF(
    150,
    20,
    1.3f * width,
    1.3f * height);

// Draw a portion of the image. Scale that portion of the image
// so that it fills the destination rectangle.
RectangleF sourceRect = new RectangleF(0, 0, .75f * width, .75f * height);
e.Graphics.DrawImage(
    image,
    destinationRect,
    sourceRect,
    GraphicsUnit.Pixel);
Dim image As New Bitmap("Apple.gif")

' Draw the image unaltered with its upper-left corner at (0, 0).
e.Graphics.DrawImage(image, 0, 0)

' 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).
Dim width As Integer = image.Width
Dim height As Integer = image.Height
Dim destinationRect As New RectangleF( _
    150, _
    20, _
    1.3F * width, _
    1.3F * height)

' Draw a portion of the image. Scale that portion of the image
' so that it fills the destination rectangle.
Dim sourceRect As New RectangleF(0, 0, 0.75F * width, 0.75F * height)
e.Graphics.DrawImage( _
    image, _
    destinationRect, _
    sourceRect, _
    GraphicsUnit.Pixel)

編譯程式碼

上述範例是為了搭配 Windows Form 使用而設計,且其需要 PaintEventArgse,這是 Paint 事件處理常式的參數。 請務必將 取代 Apple.gif 為您系統上有效的映射檔名稱和路徑。

另請參閱