共用方式為


裁剪與縮放影像的方法

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

範例

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

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

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

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

原始影像和裁剪相同影像的螢幕擷取畫面。

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 Forms 使用而設計,且其需要 PaintEventArgse,這是 Paint 事件處理常式的參數。 請務必將 Apple.gif 取代為您系統上有效的影像檔案名稱和路徑。

另請參閱