Share via


HOW TO:裁剪和縮放影像

更新:2007 年 11 月

Graphics 類別提供了幾個 DrawImage 方法,有些方法的來源和目的端矩形參數可用來裁切和縮放影像。

範例

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

DrawImage 方法會查看來源矩形,決定要繪製的蘋果部分,來源矩形是由第三、第四、第五和第六個引數來指定。在這種情況下,會將蘋果的寬度裁切為 75%,高度也會裁切為 75%。

DrawImage 方法也會查看目的端矩形,決定繪製裁切蘋果的位置和裁切蘋果的大小,目的端矩形是由第二個引數來指定。在這種情況下,目的端矩形的寬度會比原始影像寬 30%,長度也會比原始影像長 30%。

下圖顯示的是原始的蘋果以及縮放和裁切過的蘋果。

裁剪 & 縮放

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)

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);

編譯程式碼

上述範例是專為與 Windows Form 搭配使用而設計的,而且它需要 PaintEventArgs e (即 Paint 事件處理常式的參數)。請以系統中有效的影像檔名稱和路徑取代 Apple.gif。

請參閱

其他資源

影像、點陣圖和中繼檔

使用影像、點陣圖、圖示和中繼檔