Observação
O acesso a essa página exige autorização. Você pode tentar entrar ou alterar diretórios.
O acesso a essa página exige autorização. Você pode tentar alterar os diretórios.
A Graphics classe fornece vários DrawImage métodos, alguns dos quais têm parâmetros de retângulo de origem e destino que você pode usar para cortar e dimensionar imagens.
Exemplo
O exemplo a seguir constrói um Image objeto do arquivo de disco Apple.gif. O código desenha toda a imagem da apple em seu tamanho original. Depois, o código chama o método DrawImage de um objeto Graphics para desenhar uma parte da imagem da maçã em um retângulo de destino maior que a imagem original da maçã.
O DrawImage método determina qual parte da maçã desenhar examinando o retângulo de origem, que é especificado pelo terceiro, quarto, quinto e sexto argumentos. Nesse caso, a maçã é cortada para 75% de sua largura e 75% de sua altura.
O método DrawImage determina, ao examinar o retângulo de destino especificado pelo segundo argumento, onde desenhar a maçã cortada e o tamanho da maçã cortada. Nesse caso, o retângulo de destino é 30% maior e 30% mais alto que a imagem original.
A imagem a seguir mostra a maçã original e a maçã dimensionada e cortada.
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)
Compilando o código
O exemplo anterior foi projetado para uso com o Windows Forms e requer PaintEventArgse
, que é um parâmetro do manipulador de eventos Paint. Certifique-se de substituir Apple.gif
por um nome de arquivo de imagem e um caminho válidos em seu sistema.
Consulte também
.NET Desktop feedback