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

下图显示了这三张图片。

Scaling

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)

下图显示了未缩放的图像,以及缩小和放大的图像部分。

Cropping and Scaling

另请参阅