Pintando com imagens, desenhos e visuaisPainting with Images, Drawings, and Visuals

Este tópico descreve como usar ImageBrush, DrawingBrush, e VisualBrush objetos para pintar uma área com uma imagem, um Drawing, ou um Visual.This topic describes how to use ImageBrush, DrawingBrush, and VisualBrush objects to paint an area with an image, a Drawing, or a Visual.

Pré-requisitosPrerequisites

Para entender esse tópico, você deve estar familiarizado com os diferentes tipos de pincéis que Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF) fornece e seus recursos básicos.To understand this topic, you should be familiar with the different types of brushes Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF) provides and their basic features. Para uma introdução, consulte a Visão geral de pincéis do WPF.For an introduction, see the WPF Brushes Overview.

Pintar uma área com uma imagemPaint an Area with an Image

Um ImageBrush pinta uma área com um ImageSource.An ImageBrush paints an area with an ImageSource. O tipo mais comum de ImageSource para usar com um ImageBrush é um BitmapImage, que descreve um gráfico de bitmap.The most common type of ImageSource to use with an ImageBrush is a BitmapImage, which describes a bitmap graphic. Você pode usar um DrawingImage para pintar usando um Drawing objeto, mas é mais simples usar uma DrawingBrush em vez disso.You can use a DrawingImage to paint using a Drawing object, but it is simpler to use a DrawingBrush instead. Para obter mais informações sobre ImageSource objetos, consulte o Imaging Overview.For more information about ImageSource objects, see the Imaging Overview.

Para pintar com um ImageBrush, crie um BitmapImage e usá-lo para carregar o conteúdo do bitmap.To paint with an ImageBrush, create a BitmapImage and use it to load the bitmap content. Em seguida, use o BitmapImage para definir o ImageSource propriedade o ImageBrush.Then, use the BitmapImage to set the ImageSource property of the ImageBrush. Finalmente, aplique o ImageBrush para o objeto que deseja pintar.Finally, apply the ImageBrush to the object you want to paint. Em XAML (linguagem XAML)Extensible Application Markup Language (XAML), você pode apenas definir o ImageSource propriedade o ImageBrush com o caminho da imagem para carregar.In XAML (linguagem XAML)Extensible Application Markup Language (XAML), you can also just set the ImageSource property of the ImageBrush with the path of the image to load.

Como todos os Brush objetos, um ImageBrush pode ser usado para pintar objetos, como formas, painéis, controles e texto.Like all Brush objects, an ImageBrush can be used to paint objects such as shapes, panels, controls, and text. A ilustração a seguir mostra alguns efeitos que podem ser obtidos com um ImageBrush.The following illustration shows some effects that can be achieved with an ImageBrush.

Exemplos de saída de ImageBrushImageBrush output examples
Objetos pintados por um ImageBrushObjects painted by an ImageBrush

Por padrão, um ImageBrush alonga sua imagem para preencher completamente a área que está sendo pintada, possivelmente distorcendo a imagem se a área pintada tiver uma taxa de proporção diferente que a imagem.By default, an ImageBrush stretches its image to completely fill the area being painted, possibly distorting the image if the painted area has a different aspect ratio than the image. Você pode alterar esse comportamento alterando a Stretch propriedade do seu valor padrão de Fill para None, Uniform, ou UniformToFill.You can change this behavior by changing the Stretch property from its default value of Fill to None, Uniform, or UniformToFill. Porque ImageBrush é um tipo de TileBrush, você pode especificar exatamente como um pincel de imagem preenche a área de saída e até mesmo cria padrões.Because ImageBrush is a type of TileBrush, you can specify exactly how an image brush fills the output area and even create patterns. Para obter mais informações sobre avançadas TileBrush recursos, consulte o TileBrush Overview.For more information about advanced TileBrush features, see the TileBrush Overview.

Exemplo: pintar um objeto com uma imagem de bitmapExample: Paint an Object with a Bitmap Image

O exemplo a seguir usa uma ImageBrush para pintar o Background de um Canvas.The following example uses an ImageBrush to paint the Background of a Canvas.

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  x:Class="Microsoft.Samples.BrushExamples.ImageBrushExample"
  WindowTitle="ImageBrush Example"
  Background="White">

  <StackPanel>

    <Canvas
      Height="200" Width="300">
      <Canvas.Background>
        <ImageBrush ImageSource="sampleImages\Waterlilies.jpg" />
      </Canvas.Background>
    </Canvas>

    
  </StackPanel>
</Page>
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Microsoft.Samples.BrushExamples
{

    public class ImageBrushExample : Page
    {
    
        public ImageBrushExample()
        {
        
            StackPanel mainPanel = new StackPanel();
            canvasBackgroundExample(mainPanel);
            this.Content = mainPanel;
        
        }
                 

        private void canvasBackgroundExample(Panel mainPanel)
        {
            
            BitmapImage theImage = new BitmapImage
                (new Uri("sampleImages\\Waterlilies.jpg", UriKind.Relative));
            
            ImageBrush myImageBrush = new ImageBrush(theImage);
            
            Canvas myCanvas = new Canvas();
            myCanvas.Width = 300;
            myCanvas.Height = 200;
            myCanvas.Background = myImageBrush;
            
            mainPanel.Children.Add(myCanvas);
    
    
        }
    
    }

}

Imports Microsoft.VisualBasic
Imports System
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Media
Imports System.Windows.Media.Imaging

Namespace Microsoft.Samples.BrushExamples

	Public Class ImageBrushExample
		Inherits Page

		Public Sub New()

			Dim mainPanel As New StackPanel()
			canvasBackgroundExample(mainPanel)
			Me.Content = mainPanel

		End Sub


		Private Sub canvasBackgroundExample(ByVal mainPanel As Panel)

			Dim theImage As New BitmapImage(New Uri("sampleImages\Waterlilies.jpg", UriKind.Relative))

			Dim myImageBrush As New ImageBrush(theImage)

			Dim myCanvas As New Canvas()
			myCanvas.Width = 300
			myCanvas.Height = 200
			myCanvas.Background = myImageBrush

			mainPanel.Children.Add(myCanvas)


		End Sub

	End Class

End Namespace

Pintar uma área com um desenhoPaint an Area with a Drawing

Um DrawingBrush permite pintar uma área com formas, texto, imagens e vídeo.A DrawingBrush enables you to paint an area with shapes, text, images, and video. Formas dentro de um pincel de desenho podem ser próprias pintadas com uma cor sólida, gradiente, imagem, ou até mesmo de outro DrawingBrush.Shapes inside a drawing brush may themselves be painted with a solid color, gradient, image, or even another DrawingBrush. A ilustração a seguir demonstra alguns usos de um DrawingBrush.The following illustration demonstrates some uses of a DrawingBrush.

Exemplos de saída de DrawingBrushDrawingBrush output examples
Objetos pintados por um DrawingBrushObjects painted by a DrawingBrush

Um DrawingBrush pinta uma área com um Drawing objeto.A DrawingBrush paints an area with a Drawing object. Um Drawing objeto descreve conteúdo visível, como uma forma, bitmap, vídeo ou uma linha de texto.A Drawing object describes visible content, such as a shape, bitmap, video, or a line of text. Diferentes tipos de desenhos descrevem diferentes tipos de conteúdo.Different types of drawings describe different types of content. A seguir está uma lista dos diferentes tipos de objetos de desenho.The following is a list of the different types of drawing objects.

Para obter mais informações sobre Drawing objetos, consulte o visão geral de objetos de desenho.For more information about Drawing objects, see the Drawing Objects Overview.

Como um ImageBrush, um DrawingBrush alonga seu Drawing para preencher sua área de saída.Like an ImageBrush, a DrawingBrush stretches its Drawing to fill its output area. Você pode substituir esse comportamento alterando a Stretch propriedade da sua configuração padrão de Fill.You can override this behavior by changing the Stretch property from its default setting of Fill. Para obter mais informações, consulte a propriedade Stretch.For more information, see the Stretch property.

Exemplo: pintar um objeto com um desenhoExample: Paint an Object with a Drawing

O exemplo a seguir mostra como pintar um objeto com um desenho de três elipses.The following example shows how to paint an object with a drawing of three ellipses. Um GeometryDrawing é usado para descrever as reticências.A GeometryDrawing is used to describe the ellipses.

<Button Content="A Button">
  <Button.Background>
    <DrawingBrush>
      <DrawingBrush.Drawing>
        <GeometryDrawing Brush="LightBlue">
          <GeometryDrawing.Geometry>
            <GeometryGroup>
              <EllipseGeometry RadiusX="12.5" RadiusY="25" Center="25,50" />
              <EllipseGeometry RadiusX="12.5" RadiusY="25" Center="50,50" />
              <EllipseGeometry RadiusX="12.5" RadiusY="25" Center="75,50" />
            </GeometryGroup>
          </GeometryDrawing.Geometry>
          <GeometryDrawing.Pen>
            <Pen Thickness="1" Brush="Gray" />
          </GeometryDrawing.Pen>
        </GeometryDrawing>
      </DrawingBrush.Drawing>
    </DrawingBrush>
  </Button.Background>
</Button>
// Create a DrawingBrush.
DrawingBrush myDrawingBrush = new DrawingBrush();

// Create a drawing.
GeometryDrawing myGeometryDrawing = new GeometryDrawing();
myGeometryDrawing.Brush = Brushes.LightBlue;
myGeometryDrawing.Pen = new Pen(Brushes.Gray, 1);
GeometryGroup ellipses = new GeometryGroup();
ellipses.Children.Add(new EllipseGeometry(new Point(25,50), 12.5, 25));
ellipses.Children.Add(new EllipseGeometry(new Point(50,50), 12.5, 25));
ellipses.Children.Add(new EllipseGeometry(new Point(75,50), 12.5, 25));

myGeometryDrawing.Geometry = ellipses;
myDrawingBrush.Drawing = myGeometryDrawing;

Button myButton = new Button();
myButton.Content = "A Button";

// Use the DrawingBrush to paint the button's background.
myButton.Background = myDrawingBrush;
' Create a DrawingBrush.
Dim myDrawingBrush As New DrawingBrush()

' Create a drawing.
Dim myGeometryDrawing As New GeometryDrawing()
myGeometryDrawing.Brush = Brushes.LightBlue
myGeometryDrawing.Pen = New Pen(Brushes.Gray, 1)
Dim ellipses As New GeometryGroup()
ellipses.Children.Add(New EllipseGeometry(New Point(25,50), 12.5, 25))
ellipses.Children.Add(New EllipseGeometry(New Point(50,50), 12.5, 25))
ellipses.Children.Add(New EllipseGeometry(New Point(75,50), 12.5, 25))

myGeometryDrawing.Geometry = ellipses
myDrawingBrush.Drawing = myGeometryDrawing

Dim myButton As New Button()
myButton.Content = "A Button"

' Use the DrawingBrush to paint the button's background.
myButton.Background = myDrawingBrush

Pintar uma área com um visualPaint an Area with a Visual

O mais versátil e eficiente de todos os cursores, o VisualBrush pinta uma área com um Visual.The most versatile and powerful of all the brushes, the VisualBrush paints an area with a Visual. Um Visual é um tipo de gráfico de baixo nível que serve como o predecessor de vários componentes gráficos úteis.A Visual is a low-level graphical type that serves as the ancestor of many useful graphical components. Por exemplo, o Window, FrameworkElement, e Control classes são todos os tipos de Visual objetos.For example, the Window, FrameworkElement, and Control classes are all types of Visual objects. Usando um VisualBrush, você pode pintar áreas com praticamente qualquer Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF) objeto gráfico.Using a VisualBrush, you can paint areas with almost any Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF) graphical object.

Observação

Embora VisualBrush é um tipo de Freezable do objeto, ele não pode ser congelado (somente leitura) quando sua Visual propriedade é definida como um valor diferente de null.Although VisualBrush is a type of Freezable object, it cannot be frozen (made read-only) when its Visual property is set to a value other than null.

Há duas maneiras para especificar o Visual conteúdo de um VisualBrush.There are two ways to specify the Visual content of a VisualBrush.

Quando você define um novo Visual para um VisualBrush e que Visual é um UIElement (como um painel ou controle), o sistema de layout é executado UIElement e seus elementos filhos quando o AutoLayoutContent está definida como true.When you define a new Visual for a VisualBrush and that Visual is a UIElement (such as a panel or control), the layout system runs on the UIElement and its child elements when the AutoLayoutContent property is set to true. No entanto, a raiz UIElement é essencialmente isolada do restante do sistema: estilos e layout externo não podem permear esse limite.However, the root UIElement is essentially isolated from the rest of the system: styles, and external layout can't permeate this boundary. Portanto, você deve especificar explicitamente o tamanho da raiz UIElement, porque seu único pai é o VisualBrush e, portanto, ele não pode automaticamente redimensionar a mesmo para a área que está sendo pintada.Therefore, you should explicitly specify the size of the root UIElement, because its only parent is the VisualBrush and therefore it cannot automatically size itself to the area being painted. Para mais informações sobre o layout em Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF), consulte Layout.For more information about layout in Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF), see the Layout.

Como ImageBrush e DrawingBrush, um VisualBrush alonga seu conteúdo para preencher sua área de saída.Like ImageBrush and DrawingBrush, a VisualBrush stretches its content to fill its output area. Você pode substituir esse comportamento alterando a Stretch propriedade da sua configuração padrão de Fill.You can override this behavior by changing the Stretch property from its default setting of Fill. Para obter mais informações, consulte a propriedade Stretch.For more information, see the Stretch property.

Exemplo: pintar um objeto com um visualExample: Paint an Object with a Visual

No exemplo a seguir, vários controles e um painel são usados para pintar um retângulo.In the following example, several controls and a panel are used to paint a rectangle.

<Rectangle Width="150" Height="150" Stroke="Black" Margin="5,0,5,0">
  <Rectangle.Fill>
    <VisualBrush>
      <VisualBrush.Visual>
        <StackPanel Background="White">
          <Rectangle Width="25" Height="25" Fill="Red" Margin="2" />
          <TextBlock FontSize="10pt" Margin="2">Hello, World!</TextBlock>
          <Button Margin="2">A Button</Button>
        </StackPanel>
      </VisualBrush.Visual>
    </VisualBrush>
  </Rectangle.Fill>
</Rectangle>
VisualBrush myVisualBrush = new VisualBrush();

// Create the visual brush's contents.
StackPanel myStackPanel = new StackPanel();
myStackPanel.Background = Brushes.White;

Rectangle redRectangle = new Rectangle();
redRectangle.Width = 25;
redRectangle.Height =25; 
redRectangle.Fill = Brushes.Red;
redRectangle.Margin = new Thickness(2);
myStackPanel.Children.Add(redRectangle);

TextBlock someText = new TextBlock();
FontSizeConverter myFontSizeConverter = new FontSizeConverter();
someText.FontSize = (double)myFontSizeConverter.ConvertFrom("10pt");
someText.Text = "Hello, World!";
someText.Margin = new Thickness(2);
myStackPanel.Children.Add(someText);

Button aButton = new Button();
aButton.Content = "A Button";
aButton.Margin = new Thickness(2);
myStackPanel.Children.Add(aButton);

// Use myStackPanel as myVisualBrush's content.
myVisualBrush.Visual = myStackPanel;

// Create a rectangle to paint.
Rectangle myRectangle = new Rectangle();
myRectangle.Width = 150;
myRectangle.Height = 150;
myRectangle.Stroke = Brushes.Black;
myRectangle.Margin = new Thickness(5,0,5,0);

// Use myVisualBrush to paint myRectangle.
myRectangle.Fill = myVisualBrush;

Dim myVisualBrush As New VisualBrush()

' Create the visual brush's contents.
Dim myStackPanel As New StackPanel()
myStackPanel.Background = Brushes.White

         Dim redRectangle As New Rectangle()
         With redRectangle
             .Width = 25
             .Height = 25
             .Fill = Brushes.Red
             .Margin = New Thickness(2)
         End With
         myStackPanel.Children.Add(redRectangle)

         Dim someText As New TextBlock()
         Dim myFontSizeConverter As New FontSizeConverter()
         someText.FontSize = CDbl(myFontSizeConverter.ConvertFrom("10pt"))
         someText.Text = "Hello, World!"
         someText.Margin = New Thickness(2)
         myStackPanel.Children.Add(someText)

         Dim aButton As New Button()
         aButton.Content = "A Button"
         aButton.Margin = New Thickness(2)
         myStackPanel.Children.Add(aButton)

         ' Use myStackPanel as myVisualBrush's content.
         myVisualBrush.Visual = myStackPanel

         ' Create a rectangle to paint.
         Dim myRectangle As New Rectangle()
         With myRectangle
             .Width = 150
             .Height = 150
             .Stroke = Brushes.Black
             .Margin = New Thickness(5, 0, 5, 0)
         End With

         ' Use myVisualBrush to paint myRectangle.
         myRectangle.Fill = myVisualBrush

Exemplo: criar um reflexoExample: Create a Reflection

O exemplo anterior mostrou como criar um novo Visual para uso como um plano de fundo.The preceding example showed how to create a new Visual for use as a background. Você também pode usar um VisualBrush para exibir um visual existente; esse recurso permite que você produzir efeitos visuais interessantes, como reflexos e ampliação.You can also use a VisualBrush to display an existing visual; this capability enables you to produce interesting visual effects, such as reflections and magnification. O exemplo a seguir usa uma VisualBrush para criar um reflexo de um Border que contém vários elementos.The following example uses a VisualBrush to create a reflection of a Border that contains several elements. A ilustração a seguir mostra a saída que esse exemplo produz.The following illustration shows the output that this example produces.

Um objeto Visual de refletidasA reflected Visual object
Um objeto visual refletidoA reflected Visual object

using System;
using System.Windows;
using System.Windows.Data;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.IO;
using System.Collections.ObjectModel;
using System.Windows.Shapes;
namespace SDKSample
{
    public partial class ReflectionExample : Page
    {
        public ReflectionExample()
        {
            // Create a name scope for the page.
            NameScope.SetNameScope(this, new NameScope());

            this.Background = Brushes.Black;
            StackPanel myStackPanel = new StackPanel();
            myStackPanel.Margin = new Thickness(50);

            Border myReflectedBorder = new Border();
            this.RegisterName("ReflectedVisual", myReflectedBorder);

            // Create a gradient background for the border.
            GradientStop firstStop = new GradientStop();
            firstStop.Offset = 0.0;
            Color firstStopColor = new Color();
            firstStopColor.R = 204;
            firstStopColor.G = 204;
            firstStopColor.B = 255;
            firstStopColor.A = 255;
            firstStop.Color = firstStopColor;
            GradientStop secondStop = new GradientStop();
            secondStop.Offset = 1.0;
            secondStop.Color = Colors.White;

            GradientStopCollection myGradientStopCollection = new GradientStopCollection();
            myGradientStopCollection.Add(firstStop);
            myGradientStopCollection.Add(secondStop);

            LinearGradientBrush myLinearGradientBrush = new LinearGradientBrush();
            myLinearGradientBrush.StartPoint = new Point(0, 0.5);
            myLinearGradientBrush.EndPoint = new Point(1, 0.5);
            myLinearGradientBrush.GradientStops = myGradientStopCollection;

            myReflectedBorder.Background = myLinearGradientBrush;

            // Add contents to the border.
            StackPanel borderStackPanel = new StackPanel();
            borderStackPanel.Orientation = Orientation.Horizontal;
            borderStackPanel.Margin = new Thickness(10);

            TextBlock myTextBlock = new TextBlock();
            myTextBlock.TextWrapping = TextWrapping.Wrap;
            myTextBlock.Width = 200;
            myTextBlock.Text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit." +
                               " Suspendisse vel ante. Donec luctus tortor sit amet est." +
                               " Nullam pulvinar odio et wisi." +
                               " Pellentesque quis magna. Sed pellentesque." +
                               " Nulla euismod." +
                               "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.";

            borderStackPanel.Children.Add(myTextBlock);

            StackPanel ellipseStackPanel = new StackPanel();

            Ellipse ellipse1 = new Ellipse();
            ellipse1.Margin = new Thickness(10);
            ellipse1.Height = 50;
            ellipse1.Width = 50;
            ellipse1.Fill = Brushes.Black;
            ellipseStackPanel.Children.Add(ellipse1);
            Ellipse ellipse2 = new Ellipse();
            ellipse2.Margin = new Thickness(10);
            ellipse2.Height = 50;
            ellipse2.Width = 50;
            ellipse2.Fill = Brushes.Black;
            ellipseStackPanel.Children.Add(ellipse2);
            Ellipse ellipse3 = new Ellipse();
            ellipse3.Margin = new Thickness(10);
            ellipse3.Height = 50;
            ellipse3.Width = 50;
            ellipse3.Fill = Brushes.Black;
            ellipseStackPanel.Children.Add(ellipse3);
            borderStackPanel.Children.Add(ellipseStackPanel);

            myReflectedBorder.Child = borderStackPanel;

            // Create divider rectangle
            Rectangle dividerRectangle = new Rectangle();
            dividerRectangle.Height = 1;
            dividerRectangle.Fill = Brushes.Gray;
            dividerRectangle.HorizontalAlignment = HorizontalAlignment.Stretch;

            // Create the object to contain the reflection.
            Rectangle reflectionRectangle = new Rectangle();

            // Bind the height of the rectangle to the border height.
            Binding heightBinding = new Binding();
            heightBinding.ElementName = "ReflectedVisual";
            heightBinding.Path = new PropertyPath(Rectangle.HeightProperty);
            BindingOperations.SetBinding(reflectionRectangle, Rectangle.HeightProperty, heightBinding);

            // Bind the width of the rectangle to the border width.
            Binding widthBinding = new Binding();
            widthBinding.ElementName = "ReflectedVisual";
            widthBinding.Path = new PropertyPath(Rectangle.WidthProperty);
            BindingOperations.SetBinding(reflectionRectangle, Rectangle.WidthProperty, widthBinding);

            // Creates the reflection.
            VisualBrush myVisualBrush = new VisualBrush();
            myVisualBrush.Opacity = 0.75;
            myVisualBrush.Stretch = Stretch.None;
            Binding reflectionBinding = new Binding();
            reflectionBinding.ElementName = "ReflectedVisual";
            BindingOperations.SetBinding(myVisualBrush, VisualBrush.VisualProperty, reflectionBinding);

            ScaleTransform myScaleTransform = new ScaleTransform();
            myScaleTransform.ScaleX = 1;
            myScaleTransform.ScaleY = -1;
            TranslateTransform myTranslateTransform = new TranslateTransform();
            myTranslateTransform.Y = 1;

            TransformGroup myTransformGroup = new TransformGroup();
            myTransformGroup.Children.Add(myScaleTransform);
            myTransformGroup.Children.Add(myTranslateTransform);

            myVisualBrush.RelativeTransform = myTransformGroup;

            reflectionRectangle.Fill = myVisualBrush;

            // Create a gradient background for the border.
            GradientStop firstStop2 = new GradientStop();
            firstStop2.Offset = 0.0;
            Color c1 = new Color();
            c1.R = 0;
            c1.G = 0;
            c1.B = 0;
            c1.A = 255;
            firstStop2.Color = c1;
            GradientStop secondStop2 = new GradientStop();
            secondStop2.Offset = 0.5;
            Color c2 = new Color();
            c2.R = 0;
            c2.G = 0;
            c2.B = 0;
            c2.A = 51;
            firstStop2.Color = c2;
            GradientStop thirdStop = new GradientStop();
            thirdStop.Offset = 0.75;
            Color c3 = new Color();
            c3.R = 0;
            c3.G = 0;
            c3.B = 0;
            c3.A = 0;
            thirdStop.Color = c3;

            GradientStopCollection myGradientStopCollection2 = new GradientStopCollection();
            myGradientStopCollection2.Add(firstStop2);
            myGradientStopCollection2.Add(secondStop2);
            myGradientStopCollection2.Add(thirdStop);

            LinearGradientBrush myLinearGradientBrush2 = new LinearGradientBrush();
            myLinearGradientBrush2.StartPoint = new Point(0.5, 0);
            myLinearGradientBrush2.EndPoint = new Point(0.5, 1);
            myLinearGradientBrush2.GradientStops = myGradientStopCollection2;

            reflectionRectangle.OpacityMask = myLinearGradientBrush2;

            BlurBitmapEffect myBlurBitmapEffect = new BlurBitmapEffect();
            myBlurBitmapEffect.Radius = 1.5;

            reflectionRectangle.BitmapEffect = myBlurBitmapEffect;

            myStackPanel.Children.Add(myReflectedBorder);
            myStackPanel.Children.Add(dividerRectangle);
            myStackPanel.Children.Add(reflectionRectangle);
            this.Content = myStackPanel;

        }
        /*
    <Rectangle 
      Height="{Binding Path=ActualHeight, ElementName=ReflectedVisual}" 
      Width="{Binding Path=ActualWidth, ElementName=ReflectedVisual}">

      <Rectangle.OpacityMask>
        <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
          <GradientStop Color="#FF000000" Offset="0.0" />
          <GradientStop Color="#33000000" Offset="0.5" />
          <GradientStop Color="#00000000" Offset="0.75" />
        </LinearGradientBrush>
      </Rectangle.OpacityMask>

      <Rectangle.BitmapEffect>
        <BlurBitmapEffect Radius="1.5" />
      </Rectangle.BitmapEffect>
      
    </Rectangle>
  </StackPanel>
</Page>

*/
        
    }
}

Imports System
Imports System.Windows
Imports System.Windows.Data
Imports System.Windows.Controls
Imports System.Windows.Media
Imports System.Windows.Media.Effects
Imports System.Windows.Media.Imaging
Imports System.IO
Imports System.Collections.ObjectModel
Imports System.Windows.Shapes
Namespace SDKSample
	Partial Public Class ReflectionExample
		Inherits Page
		Public Sub New()
			' Create a name scope for the page.
			NameScope.SetNameScope(Me, New NameScope())

			Me.Background = Brushes.Black
			Dim myStackPanel As New StackPanel()
			myStackPanel.Margin = New Thickness(50)

			Dim myReflectedBorder As New Border()
			Me.RegisterName("ReflectedVisual", myReflectedBorder)

			' Create a gradient background for the border.
			Dim firstStop As New GradientStop()
			firstStop.Offset = 0.0
			Dim firstStopColor As New Color()
			firstStopColor.R = 204
			firstStopColor.G = 204
			firstStopColor.B = 255
			firstStopColor.A = 255
			firstStop.Color = firstStopColor
			Dim secondStop As New GradientStop()
			secondStop.Offset = 1.0
			secondStop.Color = Colors.White

			Dim myGradientStopCollection As New GradientStopCollection()
			myGradientStopCollection.Add(firstStop)
			myGradientStopCollection.Add(secondStop)

			Dim myLinearGradientBrush As New LinearGradientBrush()
			myLinearGradientBrush.StartPoint = New Point(0, 0.5)
			myLinearGradientBrush.EndPoint = New Point(1, 0.5)
			myLinearGradientBrush.GradientStops = myGradientStopCollection

			myReflectedBorder.Background = myLinearGradientBrush

			' Add contents to the border.
			Dim borderStackPanel As New StackPanel()
			borderStackPanel.Orientation = Orientation.Horizontal
			borderStackPanel.Margin = New Thickness(10)

			Dim myTextBlock As New TextBlock()
			myTextBlock.TextWrapping = TextWrapping.Wrap
			myTextBlock.Width = 200
			myTextBlock.Text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit." & " Suspendisse vel ante. Donec luctus tortor sit amet est." & " Nullam pulvinar odio et wisi." & " Pellentesque quis magna. Sed pellentesque." & " Nulla euismod." & "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas."

			borderStackPanel.Children.Add(myTextBlock)

			Dim ellipseStackPanel As New StackPanel()

			Dim ellipse1 As New Ellipse()
			ellipse1.Margin = New Thickness(10)
			ellipse1.Height = 50
			ellipse1.Width = 50
			ellipse1.Fill = Brushes.Black
			ellipseStackPanel.Children.Add(ellipse1)
			Dim ellipse2 As New Ellipse()
			ellipse2.Margin = New Thickness(10)
			ellipse2.Height = 50
			ellipse2.Width = 50
			ellipse2.Fill = Brushes.Black
			ellipseStackPanel.Children.Add(ellipse2)
			Dim ellipse3 As New Ellipse()
			ellipse3.Margin = New Thickness(10)
			ellipse3.Height = 50
			ellipse3.Width = 50
			ellipse3.Fill = Brushes.Black
			ellipseStackPanel.Children.Add(ellipse3)
			borderStackPanel.Children.Add(ellipseStackPanel)

			myReflectedBorder.Child = borderStackPanel

			' Create divider rectangle
			Dim dividerRectangle As New Rectangle()
			dividerRectangle.Height = 1
			dividerRectangle.Fill = Brushes.Gray
			dividerRectangle.HorizontalAlignment = HorizontalAlignment.Stretch

			' Create the object to contain the reflection.
			Dim reflectionRectangle As New Rectangle()

			' Bind the height of the rectangle to the border height.
			Dim heightBinding As New Binding()
			heightBinding.ElementName = "ReflectedVisual"
			heightBinding.Path = New PropertyPath(Rectangle.HeightProperty)
			BindingOperations.SetBinding(reflectionRectangle, Rectangle.HeightProperty, heightBinding)

			' Bind the width of the rectangle to the border width.
			Dim widthBinding As New Binding()
			widthBinding.ElementName = "ReflectedVisual"
			widthBinding.Path = New PropertyPath(Rectangle.WidthProperty)
			BindingOperations.SetBinding(reflectionRectangle, Rectangle.WidthProperty, widthBinding)

			' Creates the reflection.
			Dim myVisualBrush As New VisualBrush()
			myVisualBrush.Opacity = 0.75
			myVisualBrush.Stretch = Stretch.None
			Dim reflectionBinding As New Binding()
			reflectionBinding.ElementName = "ReflectedVisual"
			BindingOperations.SetBinding(myVisualBrush, VisualBrush.VisualProperty, reflectionBinding)

			Dim myScaleTransform As New ScaleTransform()
			myScaleTransform.ScaleX = 1
			myScaleTransform.ScaleY = -1
			Dim myTranslateTransform As New TranslateTransform()
			myTranslateTransform.Y = 1

			Dim myTransformGroup As New TransformGroup()
			myTransformGroup.Children.Add(myScaleTransform)
			myTransformGroup.Children.Add(myTranslateTransform)

			myVisualBrush.RelativeTransform = myTransformGroup

			reflectionRectangle.Fill = myVisualBrush

			' Create a gradient background for the border.
			Dim firstStop2 As New GradientStop()
			firstStop2.Offset = 0.0
			Dim c1 As New Color()
			c1.R = 0
			c1.G = 0
			c1.B = 0
			c1.A = 255
			firstStop2.Color = c1
			Dim secondStop2 As New GradientStop()
			secondStop2.Offset = 0.5
			Dim c2 As New Color()
			c2.R = 0
			c2.G = 0
			c2.B = 0
			c2.A = 51
			firstStop2.Color = c2
			Dim thirdStop As New GradientStop()
			thirdStop.Offset = 0.75
			Dim c3 As New Color()
			c3.R = 0
			c3.G = 0
			c3.B = 0
			c3.A = 0
			thirdStop.Color = c3

			Dim myGradientStopCollection2 As New GradientStopCollection()
			myGradientStopCollection2.Add(firstStop2)
			myGradientStopCollection2.Add(secondStop2)
			myGradientStopCollection2.Add(thirdStop)

			Dim myLinearGradientBrush2 As New LinearGradientBrush()
			myLinearGradientBrush2.StartPoint = New Point(0.5, 0)
			myLinearGradientBrush2.EndPoint = New Point(0.5, 1)
			myLinearGradientBrush2.GradientStops = myGradientStopCollection2

			reflectionRectangle.OpacityMask = myLinearGradientBrush2

			Dim myBlurBitmapEffect As New BlurBitmapEffect()
			myBlurBitmapEffect.Radius = 1.5

			reflectionRectangle.BitmapEffect = myBlurBitmapEffect

			myStackPanel.Children.Add(myReflectedBorder)
			myStackPanel.Children.Add(dividerRectangle)
			myStackPanel.Children.Add(reflectionRectangle)
			Me.Content = myStackPanel

		End Sub
    End Class
End Namespace
<Page  
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
  Background="Black">


  <StackPanel Margin="50">

    <!-- The object to reflect. -->
    <Border Name="ReflectedVisual" Width="400">
      <Border.Background>
        <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">
          <GradientStop Offset="0.0" Color="#CCCCFF" />
          <GradientStop Offset="1.0" Color="White" />
        </LinearGradientBrush>
      </Border.Background>
      <StackPanel Orientation="Horizontal" Margin="10">        
        <TextBlock TextWrapping="Wrap" Width="200" Margin="10">
          Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
          Suspendisse vel ante. Donec luctus tortor sit amet est.
          Nullam pulvinar odio et wisi.
          Pellentesque quis magna. Sed pellentesque.
          Nulla euismod.
          Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
        </TextBlock>
        <StackPanel>
          <Ellipse Margin="10" Height="50" Width="50" Fill="Black" />
          <Ellipse Margin="10" Height="50" Width="50" Fill="Black" />
          <Ellipse Margin="10" Height="50" Width="50" Fill="Black" />
        </StackPanel>
      </StackPanel>
    </Border>

    <Rectangle Height="1" Fill="Gray" HorizontalAlignment="Stretch" />

    <!-- The object to contain the reflection.-->
    <Rectangle 
      Height="{Binding Path=ActualHeight, ElementName=ReflectedVisual}" 
      Width="{Binding Path=ActualWidth, ElementName=ReflectedVisual}">
      <Rectangle.Fill>

        <!-- Creates the reflection. -->
        <VisualBrush 
          Opacity="0.75" Stretch="None"
          Visual="{Binding ElementName=ReflectedVisual}">
          <VisualBrush.RelativeTransform>

            <!-- Flip the reflection. -->
            <TransformGroup>
              <ScaleTransform ScaleX="1" ScaleY="-1" />
              <TranslateTransform  Y="1" />
            </TransformGroup>
          </VisualBrush.RelativeTransform>
        </VisualBrush>
      </Rectangle.Fill>

      <Rectangle.OpacityMask>
        <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
          <GradientStop Color="#FF000000" Offset="0.0" />
          <GradientStop Color="#33000000" Offset="0.5" />
          <GradientStop Color="#00000000" Offset="0.75" />
        </LinearGradientBrush>
      </Rectangle.OpacityMask>

      <Rectangle.BitmapEffect>
        <BlurBitmapEffect Radius="1.5" />
      </Rectangle.BitmapEffect>
      
    </Rectangle>
  </StackPanel>
</Page>

Para outros exemplos que mostram como ampliar partes da tela e como criar reflexões, consulte o Exemplo do VisualBrush.For additional examples that show how to magnify portions of the screen and how to create reflections, see the VisualBrush Sample.

Recursos do TileBrushTileBrush Features

ImageBrush, DrawingBrush, e VisualBrush são tipos de TileBrush objetos.ImageBrush, DrawingBrush, and VisualBrush are types of TileBrush objects. TileBrushobjetos oferecem uma grande quantidade de controle sobre como uma área é pintada com uma imagem, desenho ou visual.TileBrush objects provide you with a great deal of control over how an area is painted with an image, drawing, or visual. Por exemplo, em vez de apenas pintar uma área com uma única imagem alongada, você pode pintá-la com uma série de blocos de imagens que criam um padrão.For example, instead of just painting an area with a single stretched image, you can paint an area with a series of image tiles that create a pattern.

Um TileBrush tem três componentes principais: conteúdo, peças e a área de saída.A TileBrush has three primary components: content, tiles, and the output area.

Componentes de TileBrushTileBrush components
Componentes de um TileBrush com um único blocoComponents of a TileBrush with a single tile

Componentes de um TileBrush lado a ladoComponents of a tiled TileBrush
Componentes de um TileBrush com vários blocosComponents of a TileBrush with multiple tiles

Para obter mais informações sobre os recursos de lado a lado do TileBrush objetos, consulte o TileBrush Overview.For more information about the tiling features of TileBrush objects, see the TileBrush Overview.

Consulte tambémSee Also

ImageBrush
DrawingBrush
VisualBrush
TileBrush
Visão geral de TileBrushTileBrush Overview
Visão geral de pincéis do WPFWPF Brushes Overview
Visão geral da geração de imagensImaging Overview
Visão geral dos objetos de desenhoDrawing Objects Overview
Visão geral de máscaras da opacidadeOpacity Masks Overview
Visão geral de renderização de gráficos do WPFWPF Graphics Rendering Overview
Exemplo de ImageBrushImageBrush Sample
Exemplo de VisualBrushVisualBrush Sample