在 GDI+ 中裁切和缩放图像

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

DrawImage 的变体

DrawImage 方法的一个变体接收一个 Bitmap 和一个 Rectangle。 该矩形指定了绘图操作的目标,即它指定了将要在其内绘图的矩形。 如果目标矩形的大小与原始图像的大小不同,原始图像将进行缩放,以适应目标矩形。 下面的代码示例演示如何将同一图像绘制三次:一次没有缩放,一次使用扩展,一次使用压缩:

        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)

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

下面的插图显示了这三张图片。

缩放

DrawImage 方法的一些变体带有源矩形参数和目标矩形参数。 源矩形参数指定原始图像要绘制的部分。 目标矩形参数指定将要在其内绘制该图像指定部分的矩形。 如果目标矩形的大小与源矩形的大小不同,图片将会缩放,以适应目标矩形。

下面的代码示例演示如何用文件 Runner.jpg 构造 Bitmap。 整个图像在 (0,0) 处开始绘制,无缩放。 然后将该图像的一小部分绘制两次:一次使用压缩,一次使用扩展。

        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)

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

下面的插图显示了未缩放的图像,以及压缩的和扩展的图像部分。

裁剪和缩放

请参见

其他资源

图像、位图和图元文件

使用图像、位图、图标和图元文件