在 GDI+ 中裁切和缩放图像

可以使用 Graphics 类中的 DrawImage 方法来绘制和定位矢量图像及光栅图像。 DrawImage 是一种重载的方法,因此可通过多种方式提供参数。

DrawImage 变体

DrawImage 方法的一个变体接收 BitmapRectangle。 矩形指定绘图操作的目标;也就是说,它指定要在其中绘制图像的矩形。 如果目标矩形的大小与原始图像的大小不同,则会缩放图像以适应目标矩形。 下面的代码示例演示如何绘制同一个图像三次:一次没有缩放,一次使用扩展,一次使用压缩:

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 方法的某些变体具有源矩形参数和目标矩形参数。 源矩形参数指定要绘制的原始图像部分。 目标矩形定义了用于绘制图像某一部分的矩形。 如果目标矩形的大小与源矩形的大小不同,则会缩放图片以适应目标矩形。

下面的代码示例演示如何从文件 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)

下图显示了未缩放的图像以及压缩和展开的图像部分。

裁剪和缩放

另请参阅