次の方法で共有


GDI+ でのイメージのトリミングとスケーリング

DrawImage クラスの Graphics メソッドを使用して、ベクター イメージとラスター イメージを描画および配置できます。 DrawImage はオーバーロードされたメソッドであるため、引数を指定する方法はいくつかあります。

DrawImage のバリエーション

DrawImage メソッドの 1 つのバリエーションは、BitmapRectangleを受け取ります。 四角形は、描画操作の目的地を指定します。つまり、イメージを描画するための四角形を指定します。 コピー先の四角形のサイズが元のイメージのサイズと異なる場合、イメージは目的の四角形に合わせて拡大縮小されます。 次のコード例は、同じイメージを 3 回描画する方法を示しています。1 回はスケーリングなし、1 回は拡張、1 回は圧縮です。

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)

次の図は、3 つの画像を示しています。

スケーリング

DrawImage メソッドの一部のバリエーションには、ソース四角形パラメーターと、変換先の四角形パラメーターがあります。 ソース四角形パラメーターは、描画する元のイメージの部分を指定します。 描画先の矩形は、画像のその部分を描画する矩形を指定します。 コピー先の四角形のサイズが元の四角形のサイズと異なる場合、図は目的の四角形に合わせて拡大縮小されます。

次のコード例は、ファイル Runner.jpgから Bitmap を構築する方法を示しています。 イメージ全体は、(0, 0) にスケーリングなしで描画されます。 その後、イメージの小さな部分が 2 回描画されます。1 回は圧縮され、1 回は展開されます。

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)

次の図は、スケーリングされていないイメージと、圧縮および展開されたイメージ部分を示しています。

トリミングとスケーリング

こちらも参照ください