Porady: przycinanie i skalowanie obrazów

Klasa Graphics udostępnia kilka DrawImage metod, z których niektóre mają parametry prostokąta źródłowego i docelowego, których można użyć do przycinania i skalowania obrazów.

Przykład

Poniższy przykład tworzy Image obiekt z pliku disk Apple.gif. Kod rysuje cały obraz apple w oryginalnym rozmiarze. Następnie kod wywołuje DrawImage metodę Graphics obiektu, aby narysować część obrazu apple w prostokątze docelowym większym niż oryginalny obraz apple.

Metoda DrawImage określa, która część jabłka ma być rysowany, patrząc na prostokąt źródłowy, który jest określony przez trzeci, czwarty, piąty i szósty argument. W tym przypadku jabłko jest przycięte do 75 procent szerokości i 75 procent jego wysokości.

Metoda DrawImage określa, gdzie narysować przycięte jabłko i jak duże, aby przycięte jabłko, patrząc na prostokąt docelowy, który jest określony przez drugi argument. W takim przypadku prostokąt docelowy jest o 30 procent szerszy i o 30 procent wyższy niż oryginalny obraz.

Na poniższej ilustracji przedstawiono oryginalne jabłko i skalowane, przycięte jabłko.

Screenshot of an original image and the same image cropped.

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);
Dim image As 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)

Kompilowanie kodu

Powyższy przykład jest przeznaczony do użycia z formularzami Windows Forms i wymaga PaintEventArgseparametru , który jest parametrem Paint programu obsługi zdarzeń. Pamiętaj, aby zastąpić Apple.gif ciąg nazwą pliku obrazu i ścieżką prawidłową w systemie.

Zobacz też