Freigeben über


Zuschneiden und Skalieren von Bildern

Die Graphics-Klasse enthält mehrere DrawImage-Methoden, von denen einige über Parameter für Quell- und Zielrechtecke verfügen, mit deren Hilfe Sie Bilder zuschneiden und skalieren können.

Im folgenden Beispiel wird ein Image-Objekt aus der Datenträgerdatei Apple.gif erstellt. Der gesamte Apfel wird vom Code in der Originalgröße gezeichnet. Anschließend ruft der Code die DrawImage-Methode eines Graphics-Objekts auf, um einen Teil des Apfels in einem Zielrechteck zu zeichnen, das größer als das ursprüngliche Apfelbild ist.

Die DrawImage-Methode bestimmt den zu zeichnenden Teil des Apfels unter Verwendung des Quellrechtecks. Das Quellrechteck wird durch das dritte, vierte, fünfte und sechste Argument festgelegt. Der Apfel wird in diesem Fall auf 75 Prozent seiner Breite und auf 75 Prozent seiner Höhe zugeschnitten.

Die DrawImage-Methode bestimmt die Zeichenposition und die Zeichengröße des zugeschnittenen Apfels anhand des Zielrechtecks, das im zweiten Argument festgelegt wird. Das Zielrechteck ist in diesem Fall um 30 Prozent breiter und um 30 Prozent höher als das Originalbild.

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

In der folgenden Abbildung ist der Apfel in der Originaldarstellung sowie in der skalierten, zugeschnittenen Darstellung zu sehen.