在 GDI+ 中裁剪和縮放影像
您可以使用 DrawImage 類別的 Graphics 方法來繪製和定位向量影像和點陣影像。 DrawImage 是多載的方法,因此有數種方式可讓您提供引數。
DrawImage 變化
方法的 DrawImage 其中一個 Rectangle 變化會 Bitmap 接收 和 。 矩形會指定繪圖作業的目的地;也就是說,它會指定要在其中繪製影像的矩形。 如果目的矩形的大小與原始影像的大小不同,則會縮放影像以符合目的矩形。 下列程式碼範例示範如何繪製相同的影像三次:一次沒有縮放、一次具有展開,一次使用壓縮:
Bitmap myBitmap = new Bitmap("Spiral.png");
Rectangle expansionRectangle = new Rectangle(135, 10,
myBitmap.Width, myBitmap.Height);
Rectangle compressionRectangle = new Rectangle(300, 10,
myBitmap.Width / 2, myBitmap.Height / 2);
myGraphics.DrawImage(myBitmap, 10, 10);
myGraphics.DrawImage(myBitmap, expansionRectangle);
myGraphics.DrawImage(myBitmap, compressionRectangle);
Dim myBitmap As New Bitmap("Spiral.png")
Dim expansionRectangle As New Rectangle(135, 10, _
myBitmap.Width, myBitmap.Height)
Dim compressionRectangle As New Rectangle(300, 10, _
CType(myBitmap.Width / 2, Integer), CType(myBitmap.Height / 2, Integer))
myGraphics.DrawImage(myBitmap, 10, 10)
myGraphics.DrawImage(myBitmap, expansionRectangle)
myGraphics.DrawImage(myBitmap, compressionRectangle)
下圖顯示三張圖片。
方法的某些 DrawImage 變化具有 source-rectangle 參數,以及 destination-rectangle 參數。 source-rectangle 參數會指定要繪製的原始影像部分。 目的矩形會指定要在其中繪製該部分影像的矩形。 如果目的矩形的大小與來源矩形的大小不同,則會縮放圖片以符合目的地矩形。
下列程式碼範例示範如何從 File Runner.jpg 建構 Bitmap 。 繪製整個影像時沒有縮放比例(0,0)。 然後繪製影像的一小部分兩次:一次壓縮,一次具有展開。
Bitmap myBitmap = new Bitmap("Runner.jpg");
// One hand of the runner
Rectangle sourceRectangle = new Rectangle(80, 70, 80, 45);
// Compressed hand
Rectangle destRectangle1 = new Rectangle(200, 10, 20, 16);
// Expanded hand
Rectangle destRectangle2 = new Rectangle(200, 40, 200, 160);
// Draw the original image at (0, 0).
myGraphics.DrawImage(myBitmap, 0, 0);
// Draw the compressed hand.
myGraphics.DrawImage(
myBitmap, destRectangle1, sourceRectangle, GraphicsUnit.Pixel);
// Draw the expanded hand.
myGraphics.DrawImage(
myBitmap, destRectangle2, sourceRectangle, GraphicsUnit.Pixel);
Dim myBitmap As New Bitmap("Runner.jpg")
' One hand of the runner
Dim sourceRectangle As New Rectangle(80, 70, 80, 45)
' Compressed hand
Dim destRectangle1 As New Rectangle(200, 10, 20, 16)
' Expanded hand
Dim destRectangle2 As New Rectangle(200, 40, 200, 160)
' Draw the original image at (0, 0).
myGraphics.DrawImage(myBitmap, 0, 0)
' Draw the compressed hand.
myGraphics.DrawImage( _
myBitmap, destRectangle1, sourceRectangle, GraphicsUnit.Pixel)
' Draw the expanded hand.
myGraphics.DrawImage( _
myBitmap, destRectangle2, sourceRectangle, GraphicsUnit.Pixel)
下圖顯示未調整的影像,以及壓縮和展開的影像部分。
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應