次の方法で共有


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

Graphics クラスは、DrawImage メソッドをいくつか提供しています。その中には、描画元の範囲を表す四角形パラメータや、描画先の範囲を表す四角形パラメータを受け取るメソッドもあり、これらはイメージをトリミングおよびスケーリングするために使用できます。

ディスク ファイル Apple.gif から Image オブジェクトを作成する例を次に示します。このコードは、リンゴのイメージ全体を元のサイズで描画します。次に、Graphics オブジェクトの DrawImage メソッドを呼び出して、リンゴのイメージの一部を、元のリンゴのイメージよりも大きな描画先の四角形に描画します。

DrawImage メソッドは、3 番目、4 番目、5 番目、6 番目の各引数によって指定されている、描画元の範囲を表す四角形を参照し、リンゴのどの部分を描画するかを決定します。この場合は、リンゴの幅と高さがそれぞれの 75% になるようにトリミングされます。

DrawImage メソッドは、2 番目の引数によって指定されている、描画先の範囲を表す四角形を参照して、トリミングしたリンゴのイメージの描画位置と、そのイメージをどれくらいの大きさで描画するかを決定します。この例では、描画先の範囲を表す四角形は、元のイメージよりも幅、高さ共に 30% 大きく指定されています。

Dim image = New Bitmap("Apple.gif")

' Draw the image unaltered with its upper-left corner at (0, 0).
e.Graphics.DrawImage(image, 0, 0)

' Make the destination rectangle 30 percent wider and
' 30 percent taller than the original image.
' Put the upper-left corner of the destination
' rectangle at (150, 20).
Dim width As Integer = image.Width
Dim height As Integer = image.Height
Dim destinationRect As New RectangleF( _
   150, _
   20, _
   1.3F * width, _
   1.3F * height)

' Draw a portion of the image. Scale that portion of the image
' so that it fills the destination rectangle.
Dim sourceRect As New RectangleF(0, 0, 0.75F * width, 0.75F * height)
e.Graphics.DrawImage( _
   image, _
   destinationRect, _
   sourceRect, _
   GraphicsUnit.Pixel)
[C#]
Image image = new Bitmap("Apple.gif");

// Draw the image unaltered with its upper-left corner at (0, 0).
e.Graphics.DrawImage(image, 0, 0);

// Make the destination rectangle 30 percent wider and
// 30 percent taller than the original image.
// Put the upper-left corner of the destination
// rectangle at (150, 20).
int width = image.Width;
int height = image.Height;
RectangleF destinationRect =new RectangleF(
   150,
   20,
   1.3f * width,
   1.3f * height);

// Draw a portion of the image. Scale that portion of the image
// so that it fills the destination rectangle.
RectangleF sourceRect = new RectangleF(0, 0, .75f * width, .75f * height);
e.Graphics.DrawImage(
   image,
   destinationRect,
   sourceRect,
   GraphicsUnit.Pixel); 

元のリンゴと、スケーリングおよびトリミングしたリンゴを次の図に示します。