Compartir a través de


Cómo: Conservar la relación de aspecto de una imagen utilizada como fondo

En este ejemplo se muestra cómo utilizar la propiedad Stretch de ImageBrush para conservar la relación de aspecto de la imagen.

De manera predeterminada, cuando se utiliza un ImageBrush para pintar una área, su contenido se expande hasta rellenar completamente el área de salida. Cuando el área de salida y la imagen tienen relaciones de aspecto diferentes, la imagen queda distorsionada al ajustarse.

Para que ImageBrush conserve la relación de aspecto de su imagen, establezca la propiedad Stretch en Uniform o UniformToFill.

Ejemplo

En el ejemplo siguiente se utilizan dos objetos ImageBrush para pintar dos rectángulos. Cada rectángulo es de 300 por 150 píxeles y cada uno de ellos contiene una imagen de 300 por 300 píxeles. La propiedad Stretch del primer pincel se establece en Uniform, y la propiedad Stretch del segundo pincel se establece en UniformToFill.


Imports System
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Media.Imaging
Imports System.Windows.Media
Imports System.Windows.Shapes

Namespace Microsoft.Samples.Graphics.UsingImageBrush
    ''' <summary>
    ''' Demonstrates different ImageBrush Stretch settings.
    ''' </summary>
    Public Class StretchModes
        Inherits Page
        Public Sub New()

            ' Create an ImageBrush with its Stretch
            ' property set to Uniform. The image it
            ' contains will be expanded as much as possible
            ' to fill the output area while still
            ' preserving its aspect ratio.
            Dim uniformBrush As New ImageBrush()
            uniformBrush.ImageSource = New BitmapImage(New Uri("sampleImages\square.jpg", UriKind.Relative))
            uniformBrush.Stretch = Stretch.Uniform

            ' Freeze the brush (make it unmodifiable) for performance benefits.
            uniformBrush.Freeze()

            ' Create a rectangle and paint it with the ImageBrush.
            Dim rectangle1 As New Rectangle()
            With rectangle1
                .Width = 300
                .Height = 150
                .Stroke = Brushes.MediumBlue
                .StrokeThickness = 1.0
                .Fill = uniformBrush
            End With

            ' Create an ImageBrush with its Stretch
            ' property set to UniformToFill. The image it
            ' contains will be expanded to completely fill
            ' the rectangle, but its aspect ratio is preserved.
            Dim uniformToFillBrush As New ImageBrush()
            uniformToFillBrush.ImageSource = New BitmapImage(New Uri("sampleImages\square.jpg", UriKind.Relative))
            uniformToFillBrush.Stretch = Stretch.UniformToFill

            ' Freeze the brush (make it unmodifiable) for performance benefits.
            uniformToFillBrush.Freeze()

            ' Create a rectangle and paint it with the ImageBrush.
            Dim rectangle2 As New Rectangle()
            With rectangle2
                .Width = 300
                .Height = 150
                .Stroke = Brushes.MediumBlue
                .StrokeThickness = 1.0
                .Margin = New Thickness(0, 10, 0, 0)
                .Fill = uniformToFillBrush
            End With

            Dim mainPanel As New StackPanel()
            mainPanel.Children.Add(rectangle1)
            mainPanel.Children.Add(rectangle2)

            Content = mainPanel
            Background = Brushes.White
            Margin = New Thickness(20)
            Title = "ImageBrush Stretch Modes"


        End Sub
    End Class
End Namespace
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Windows.Shapes;

namespace Microsoft.Samples.Graphics.UsingImageBrush
{
    /// <summary>
    /// Demonstrates different ImageBrush Stretch settings.
    /// </summary>
    public class StretchModes : Page
    {
        public StretchModes()
        {

            // Create an ImageBrush with its Stretch
            // property set to Uniform. The image it
            // contains will be expanded as much as possible
            // to fill the output area while still
            // preserving its aspect ratio.
            ImageBrush uniformBrush = new ImageBrush();
            uniformBrush.ImageSource = 
                new BitmapImage(new Uri("sampleImages\\square.jpg", UriKind.Relative));
            uniformBrush.Stretch = Stretch.Uniform;

            // Freeze the brush (make it unmodifiable) for performance benefits.
            uniformBrush.Freeze();

            // Create a rectangle and paint it with the ImageBrush.
            Rectangle rectangle1 = new Rectangle();
            rectangle1.Width = 300;
            rectangle1.Height = 150;
            rectangle1.Stroke = Brushes.MediumBlue;
            rectangle1.StrokeThickness = 1.0;
            rectangle1.Fill = uniformBrush;

            // Create an ImageBrush with its Stretch
            // property set to UniformToFill. The image it
            // contains will be expanded to completely fill
            // the rectangle, but its aspect ratio is preserved.
            ImageBrush uniformToFillBrush = new ImageBrush();
            uniformToFillBrush.ImageSource =
                new BitmapImage(new Uri("sampleImages\\square.jpg", UriKind.Relative));
            uniformToFillBrush.Stretch = Stretch.UniformToFill;

            // Freeze the brush (make it unmodifiable) for performance benefits.
            uniformToFillBrush.Freeze();

            // Create a rectangle and paint it with the ImageBrush.
            Rectangle rectangle2 = new Rectangle();
            rectangle2.Width = 300;
            rectangle2.Height = 150;
            rectangle2.Stroke = Brushes.MediumBlue;
            rectangle2.StrokeThickness = 1.0;
            rectangle2.Margin = new Thickness(0, 10, 0, 0);
            rectangle2.Fill = uniformToFillBrush;

            StackPanel mainPanel = new StackPanel();
            mainPanel.Children.Add(rectangle1);
            mainPanel.Children.Add(rectangle2);

            Content = mainPanel;
            Background = Brushes.White;
            Margin = new Thickness(20);
            Title = "ImageBrush Stretch Modes";


        }
    }
}
<!-- Demonstrates different ImageBrush Stretch settings.-->
<Page 
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:PresentationOptions="https://schemas.microsoft.com/winfx/2006/xaml/presentation/options" 
  xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006"
  mc:Ignorable="PresentationOptions"
  Background="White" Margin="20"
  Title="ImageBrush Stretch Modes">
  <StackPanel>

    <!-- The ImageBrush in this example has its
         Stretch property set to Uniform. As a result,
         the image it contains is expanded as much as possible
         to fill the rectangle while
         still preserving its aspect ratio.-->
    <Rectangle
      Width="300" Height="150" 
      Stroke="MediumBlue" StrokeThickness="1">
      <Rectangle.Fill>
        <ImageBrush
          Stretch="Uniform" ImageSource="sampleImages\square.jpg"
          PresentationOptions:Freeze="True" />
      </Rectangle.Fill>
    </Rectangle>

    <!-- The ImageBrush in this example has its
         Stretch property set to UniformToFill. As a result,
         the image is expanded to completely fill
         the rectangle, but its aspect ratio is preserved.-->
    <Rectangle
      Width="300" Height="150"
      Stroke="MediumBlue" StrokeThickness="1"
      Margin="0,10,0,0">
      <Rectangle.Fill>
        <ImageBrush 
          Stretch="UniformToFill" ImageSource="sampleImages\square.jpg" 
          PresentationOptions:Freeze="True" />
      </Rectangle.Fill>
    </Rectangle>
  </StackPanel>
</Page>

En la ilustración siguiente se muestra la salida del primer pincel, cuya propiedad Stretch está establecida en el valor Uniform.

ImageBrush con ajuste uniforme

En la ilustración siguiente se muestra la salida del segundo pincel, cuya propiedad Stretch está establecida en el valor UniformToFill.

ImageBrush con ajuste UniformToFill

Observe que la propiedad Stretch se comporta exactamente igual para los demás objetos TileBrush, es decir, para DrawingBrush y VisualBrush. Para obtener más información sobre ImageBrush y los demás objetos TileBrush, consulte Pintar con imágenes, dibujos y elementos visuales.

Asimismo, tenga en cuenta que, aunque parezca que la propiedad Stretch especifica cómo se expandirá el contenido de TileBrush hasta ajustarse a su área de salida, en realidad especifica cómo se expande el contenido de TileBrush hasta rellenar su mosaico base. Para obtener más información, consulte TileBrush.

Este ejemplo de código forma parte de un ejemplo más extenso proporcionado para la clase ImageBrush. Para obtener el ejemplo completo, vea ImageBrush Sample.

Vea también

Referencia

TileBrush

Conceptos

Pintar con imágenes, dibujos y elementos visuales