Cenni preliminari sugli oggetti Drawing

In questo argomento vengono presentati Drawing gli oggetti e viene descritto come usarli per disegnare in modo efficiente forme, bitmap, testo e supporti. Utilizzare Drawing oggetti quando si creano clipart, disegnare con un DrawingBrushoggetto o utilizzare Visual oggetti .

Che cos'è un oggetto Disegno

Un Drawing oggetto descrive il contenuto visibile, ad esempio una forma, una bitmap, un video o una riga di testo. Tipi diversi di disegni descrivono tipi diversi di contenuto. L'elenco seguente contiene i vari tipi di oggetti Drawing.

Drawing gli oggetti sono versatili; esistono molti modi in cui è possibile usare un Drawing oggetto .

  • È possibile visualizzarlo come immagine usando un DrawingImage controllo e .Image

  • È possibile usarlo con un DrawingBrush oggetto per disegnare un oggetto, ad esempio di Background un oggetto Page.

  • È possibile usarlo per descrivere l'aspetto di un oggetto DrawingVisual.

  • È possibile usarlo per enumerare il contenuto di un oggetto Visual.

WPF fornisce altri tipi di oggetti che consentono di disegnare forme, bitmap, testo e contenuti multimediali. Ad esempio, è anche possibile usare Shape oggetti per disegnare forme e il MediaElement controllo offre un altro modo per aggiungere video all'applicazione. Quindi, quando è consigliabile usare Drawing gli oggetti? Quando è possibile sacrificare le funzionalità a livello di framework per ottenere vantaggi in termini di prestazioni o quando sono necessarie Freezable funzionalità. Poiché Drawing gli oggetti non supportano layout, input e stato attivo, offrono vantaggi in termini di prestazioni che li rendono ideali per descrivere sfondi, clipart e per disegni di basso livello con Visual oggetti.

Poiché sono un oggetto di tipo Freezable , Drawing gli oggetti ottengono diverse funzionalità speciali, tra cui le seguenti: possono essere dichiarate come risorse, condivise tra più oggetti, rese di sola lettura per migliorare le prestazioni, clonate e rese thread-safe. Per altre informazioni sulle diverse funzionalità fornite dagli Freezable oggetti, vedere Cenni preliminari sugli oggetti Freezable.

Disegnare una forma

Per disegnare una forma, utilizzare un oggetto GeometryDrawing. La proprietà di Geometry un disegno geometrico descrive la forma da disegnare, la relativa Brush proprietà descrive il modo in cui deve essere disegnato l'interno della forma e la relativa Pen proprietà descrive come disegnare il contorno.

Nell'esempio seguente viene utilizzato un oggetto GeometryDrawing per disegnare una forma. La forma è descritta da un GeometryGroup oggetto e da due EllipseGeometry oggetti . L'interno della forma viene dipinto con un LinearGradientBrush e il suo contorno viene disegnato con un oggetto BlackPen.

In questo esempio viene creato l'oggetto seguente GeometryDrawing.

A GeometryDrawing of two ellipses
GeometryDrawing

//
// Create the Geometry to draw.
//
GeometryGroup ellipses = new GeometryGroup();
ellipses.Children.Add(
    new EllipseGeometry(new Point(50,50), 45, 20)
    );
ellipses.Children.Add(
    new EllipseGeometry(new Point(50, 50), 20, 45)
    );

//
// Create a GeometryDrawing.
//
GeometryDrawing aGeometryDrawing = new GeometryDrawing();
aGeometryDrawing.Geometry = ellipses;

// Paint the drawing with a gradient.
aGeometryDrawing.Brush =
    new LinearGradientBrush(
        Colors.Blue,
        Color.FromRgb(204,204,255),
        new Point(0,0),
        new Point(1,1));

// Outline the drawing with a solid color.
aGeometryDrawing.Pen = new Pen(Brushes.Black, 10);
<GeometryDrawing>
  <GeometryDrawing.Geometry>

    <!-- Create a composite shape. -->
    <GeometryGroup>
      <EllipseGeometry Center="50,50" RadiusX="45" RadiusY="20" />
      <EllipseGeometry Center="50,50" RadiusX="20" RadiusY="45" />
    </GeometryGroup>
  </GeometryDrawing.Geometry>
  <GeometryDrawing.Brush>

    <!-- Paint the drawing with a gradient. -->
    <LinearGradientBrush>
      <GradientStop Offset="0.0" Color="Blue" />
      <GradientStop Offset="1.0" Color="#CCCCFF" />
    </LinearGradientBrush>
  </GeometryDrawing.Brush>
  <GeometryDrawing.Pen>

    <!-- Outline the drawing with a solid color. -->
    <Pen Thickness="10" Brush="Black" />
  </GeometryDrawing.Pen>
</GeometryDrawing>

Per un esempio completo, vedere Procedura: Creare un oggetto GeometryDrawing.

Altre Geometry classi, ad esempio PathGeometry consentono di creare forme più complesse creando curve e archi. Per altre informazioni sugli Geometry oggetti, vedere Cenni preliminari sulla geometria.

Per altre informazioni su altri modi per disegnare forme che non usano Drawing oggetti, vedere Cenni preliminari su forme e disegno di base in WPF.

Disegnare un'immagine

Per disegnare un'immagine, usare un oggetto ImageDrawing. La proprietà di ImageSource un ImageDrawing oggetto descrive l'immagine da disegnare e la relativa Rect proprietà definisce l'area in cui viene disegnata l'immagine.

L'esempio seguente disegna un'immagine in un rettangolo posizionata nel punto (75,75) vale a dire 100 x 100 pixel. La figura seguente mostra l'oggetto ImageDrawing creato dall'esempio. È stato aggiunto un bordo grigio per visualizzare i limiti dell'oggetto ImageDrawing.

A 100 by 100 ImageDrawing drawn at (75,75)
ImageDrawing di 100 per 100

// Create a 100 by 100 image with an upper-left point of (75,75).
ImageDrawing bigKiwi = new ImageDrawing();
bigKiwi.Rect = new Rect(75, 75, 100, 100);
bigKiwi.ImageSource = new BitmapImage(
    new Uri(@"sampleImages\kiwi.png", UriKind.Relative));
<!-- The Rect property specifies that the image only fill a 100 by 100
     rectangular area. -->
<ImageDrawing Rect="75,75,100,100" ImageSource="sampleImages\kiwi.png"/>

Per altre informazioni sulle immagini, vedere Cenni preliminari sulla creazione dell'immagine.

Riprodurre contenuti multimediali (solo codice)

Nota

Anche se puoi dichiarare un VideoDrawing oggetto in Xaml (Extensible Application Markup Language), puoi solo caricare e riprodurre i contenuti multimediali usando il codice. Per riprodurre video in Extensible Application Markup Language (XAML), usa invece un oggetto MediaElement .

Per riprodurre un file audio o video, usare e VideoDrawing .MediaPlayer È possibile caricare e riprodurre contenuti multimediali in due modi diversi. Il primo consiste nell'usare un MediaPlayer oggetto e da VideoDrawing soli e il secondo consiste nel creare un oggetto personalizzato MediaTimeline da usare con MediaPlayer e VideoDrawing.

Nota

Quando si distribuiscono contenuti multimediali con l'applicazione, non è possibile usare un file multimediale come risorsa di progetto, come avviene invece per un'immagine. È necessario invece impostare il tipo di contenuto multimediale su Content nel file del progetto e CopyToOutputDirectory su PreserveNewest o su Always.

Per riprodurre elementi multimediali senza creare il proprio MediaTimeline, seguire questa procedura.

  1. Creare un oggetto MediaPlayer.

    MediaPlayer player = new MediaPlayer();
    
  2. Usare il Open metodo per caricare il file multimediale.

    player.Open(new Uri(@"sampleMedia\xbox.wmv", UriKind.Relative));
    
  3. Creare un oggetto VideoDrawing.

    VideoDrawing aVideoDrawing = new VideoDrawing();
    
  4. Specificare le dimensioni e la posizione per disegnare il supporto impostando la Rect proprietà dell'oggetto VideoDrawing.

    aVideoDrawing.Rect = new Rect(0, 0, 100, 100);
    
  5. Impostare la Player proprietà di con l'oggetto VideoDrawingMediaPlayer creato.

    aVideoDrawing.Player = player;
    
  6. Utilizzare il Play metodo di MediaPlayer per avviare la riproduzione del supporto.

    // Play the video once.
    player.Play();
    

Nell'esempio seguente viene usato un VideoDrawing e un MediaPlayer per riprodurre un file video una sola volta.

//
// Create a VideoDrawing.
//
MediaPlayer player = new MediaPlayer();

player.Open(new Uri(@"sampleMedia\xbox.wmv", UriKind.Relative));

VideoDrawing aVideoDrawing = new VideoDrawing();

aVideoDrawing.Rect = new Rect(0, 0, 100, 100);

aVideoDrawing.Player = player;

// Play the video once.
player.Play();

Per ottenere un controllo di tempo aggiuntivo sui supporti, usare un MediaTimeline oggetto con gli MediaPlayer oggetti e VideoDrawing . MediaTimeline Consente di specificare se il video deve essere ripetuto. Per usare un MediaTimeline oggetto con , VideoDrawingseguire questa procedura:

  1. MediaTimeline Dichiarare e impostarne i comportamenti di intervallo.

    // Create a MediaTimeline.
    MediaTimeline mTimeline =
        new MediaTimeline(new Uri(@"sampleMedia\xbox.wmv", UriKind.Relative));
    
    // Set the timeline to repeat.
    mTimeline.RepeatBehavior = RepeatBehavior.Forever;
    
  2. Creare un oggetto MediaClock da MediaTimeline.

    // Create a clock from the MediaTimeline.
    MediaClock mClock = mTimeline.CreateClock();
    
  3. Creare un MediaPlayer oggetto e utilizzare per MediaClock impostare la relativa Clock proprietà.

    MediaPlayer repeatingVideoDrawingPlayer = new MediaPlayer();
    repeatingVideoDrawingPlayer.Clock = mClock;
    
  4. Creare un VideoDrawing oggetto e assegnare l'oggetto MediaPlayer alla Player proprietà dell'oggetto VideoDrawing.

    VideoDrawing repeatingVideoDrawing = new VideoDrawing();
    repeatingVideoDrawing.Rect = new Rect(150, 0, 100, 100);
    repeatingVideoDrawing.Player = repeatingVideoDrawingPlayer;
    

Nell'esempio seguente viene utilizzato un MediaTimeline oggetto con e MediaPlayer un VideoDrawing oggetto per riprodurre ripetutamente un video.

//
// Create a VideoDrawing that repeats.
//

// Create a MediaTimeline.
MediaTimeline mTimeline =
    new MediaTimeline(new Uri(@"sampleMedia\xbox.wmv", UriKind.Relative));

// Set the timeline to repeat.
mTimeline.RepeatBehavior = RepeatBehavior.Forever;

// Create a clock from the MediaTimeline.
MediaClock mClock = mTimeline.CreateClock();

MediaPlayer repeatingVideoDrawingPlayer = new MediaPlayer();
repeatingVideoDrawingPlayer.Clock = mClock;

VideoDrawing repeatingVideoDrawing = new VideoDrawing();
repeatingVideoDrawing.Rect = new Rect(150, 0, 100, 100);
repeatingVideoDrawing.Player = repeatingVideoDrawingPlayer;

Si noti che, quando si usa un MediaTimelineoggetto , si usa l'oggetto interattivo restituito ClockController dalla proprietà di MediaClock per controllare la Controller riproduzione multimediale anziché i metodi interattivi di MediaPlayer.

Creare testo

Per disegnare testo, utilizzare un GlyphRunDrawing oggetto e un oggetto GlyphRun. Nell'esempio seguente viene utilizzato un oggetto GlyphRunDrawing per disegnare il testo "Hello World".

GlyphRun theGlyphRun = new GlyphRun(
    new GlyphTypeface(new Uri(@"C:\WINDOWS\Fonts\TIMES.TTF")),
    0,
    false,
    13.333333333333334,
    new ushort[]{43, 72, 79, 79, 82, 3, 58, 82, 85, 79, 71},
    new Point(0, 12.29),
    new double[]{
        9.62666666666667, 7.41333333333333, 2.96,
        2.96, 7.41333333333333, 3.70666666666667,
        12.5866666666667, 7.41333333333333,
        4.44, 2.96, 7.41333333333333},
    null,
    null,
    null,
    null,
    null,
    null

    );

GlyphRunDrawing gDrawing = new GlyphRunDrawing(Brushes.Black, theGlyphRun);
<GlyphRunDrawing ForegroundBrush="Black">
  <GlyphRunDrawing.GlyphRun>
    <GlyphRun 
      CaretStops="{x:Null}" 
      ClusterMap="{x:Null}" 
      IsSideways="False" 
      GlyphOffsets="{x:Null}" 
      GlyphIndices="43 72 79 79 82 3 58 82 85 79 71" 
      BaselineOrigin="0,12.29"  
      FontRenderingEmSize="13.333333333333334" 
      DeviceFontName="{x:Null}" 
      AdvanceWidths="9.62666666666667 7.41333333333333 2.96 2.96 7.41333333333333 3.70666666666667 12.5866666666667 7.41333333333333 4.44 2.96 7.41333333333333" 
      BidiLevel="0">
      <GlyphRun.GlyphTypeface>
        <GlyphTypeface FontUri="C:\WINDOWS\Fonts\TIMES.TTF" />
      </GlyphRun.GlyphTypeface>
    </GlyphRun>
  </GlyphRunDrawing.GlyphRun>
</GlyphRunDrawing>

Un GlyphRun è un oggetto di basso livello destinato all'uso con scenari di presentazione e stampa di documenti in formato fisso. Un modo più semplice per disegnare testo sullo schermo consiste nell'usare un Label oggetto o .TextBlock Per altre informazioni su GlyphRun, vedere la panoramica introduttiva all'oggetto GlyphRun e agli elementi Glyphs.

Disegni composti

Un DrawingGroup oggetto consente di combinare più disegni in un singolo disegno composito. Usando un DrawingGroupoggetto , è possibile combinare forme, immagini e testo in un singolo Drawing oggetto.

Nell'esempio seguente viene utilizzato un DrawingGroup oggetto per combinare due GeometryDrawing oggetti e un ImageDrawing oggetto . Questo esempio produce il seguente output:

A DrawingGroup with multiple drawings
Disegno composto

//
// Create three drawings.
//
GeometryDrawing ellipseDrawing =
    new GeometryDrawing(
        new SolidColorBrush(Color.FromArgb(102, 181, 243, 20)),
        new Pen(Brushes.Black, 4),
        new EllipseGeometry(new Point(50,50), 50, 50)
    );

ImageDrawing kiwiPictureDrawing =
    new ImageDrawing(
        new BitmapImage(new Uri(@"sampleImages\kiwi.png", UriKind.Relative)),
        new Rect(50,50,100,100));

GeometryDrawing ellipseDrawing2 =
    new GeometryDrawing(
        new SolidColorBrush(Color.FromArgb(102,181,243,20)),
        new Pen(Brushes.Black, 4),
        new EllipseGeometry(new Point(150, 150), 50, 50)
    );

// Create a DrawingGroup to contain the drawings.
DrawingGroup aDrawingGroup = new DrawingGroup();
aDrawingGroup.Children.Add(ellipseDrawing);
aDrawingGroup.Children.Add(kiwiPictureDrawing);
aDrawingGroup.Children.Add(ellipseDrawing2);

<DrawingGroup>

  <GeometryDrawing Brush="#66B5F314">
    <GeometryDrawing.Geometry>
      <EllipseGeometry Center="50,50" RadiusX="50"  RadiusY="50"/>
    </GeometryDrawing.Geometry>
    <GeometryDrawing.Pen>
      <Pen Brush="Black" Thickness="4" />
    </GeometryDrawing.Pen>
  </GeometryDrawing>
  <ImageDrawing ImageSource="sampleImages\kiwi.png" Rect="50,50,100,100"/>
  <GeometryDrawing Brush="#66B5F314">
    <GeometryDrawing.Geometry>
      <EllipseGeometry Center="150,150" RadiusX="50"  RadiusY="50"/>
    </GeometryDrawing.Geometry>
    <GeometryDrawing.Pen>
      <Pen Brush="Black" Thickness="4" />
    </GeometryDrawing.Pen>
  </GeometryDrawing>
</DrawingGroup>

Un DrawingGroup oggetto consente inoltre di applicare maschere di opacità, trasformazioni, effetti bitmap e altre operazioni al relativo contenuto. DrawingGrouple operazioni vengono applicate nell'ordine seguente: OpacityMask, BitmapEffectOpacity, ClipGeometry, , GuidelineSete quindi Transform.

La figura seguente mostra l'ordine in cui DrawingGroup vengono applicate le operazioni.

DrawingGroup order of operations
Ordine delle operazioni DrawingGroup

Nella tabella seguente vengono descritte le proprietà che è possibile utilizzare per modificare il contenuto di un DrawingGroup oggetto.

Proprietà Descrizione Illustrazione
OpacityMask Modifica l'opacità delle parti selezionate del DrawingGroup contenuto. Per un esempio, vedere Procedura: Controllare l'opacità di un disegno. A DrawingGroup with an opacity mask
Opacity Modifica in modo uniforme l'opacità del DrawingGroup contenuto. Utilizzare questa proprietà per rendere Drawing trasparente o parzialmente trasparente. Per un esempio, vedere How to: Apply an Opacity Mask to a Drawing (Procedura: Applicare una maschera di opacità a un disegno). DrawingGroups with different opacity settings
BitmapEffect Applica un oggetto BitmapEffect al DrawingGroup contenuto. Per un esempio, vedere Procedura: Applicare un BitmapEffect a un disegno. DrawingGroup with a BlurBitmapEffect
ClipGeometry Ritaglia il contenuto in un'area DrawingGroup descritta usando un oggetto Geometry. Per un esempio, vedere Procedura: Ritagliare un disegno. DrawingGroup with a defined clip region
GuidelineSet Consente di bloccare i pixel indipendenti del dispositivo ai pixel del dispositivo lungo linee guida specificate. Questa proprietà è utile per garantire che il rendering degli elementi grafici dettagliati venga eseguito con precisione su schermi a DPI basso. Per un esempio, vedere Procedura: Applicare un GuidelineSet a un disegno. A DrawingGroup with and without a GuidelineSet
Transform Trasforma il DrawingGroup contenuto. Per un esempio, vedere How to: Apply a Transform to a Drawing (Procedura: Applicare una trasformazione a un disegno). A rotated DrawingGroup

Visualizzare un disegno come immagine

Per visualizzare un Drawing oggetto con un Image controllo , utilizzare un DrawingImage oggetto come Image controllo Source e impostare la DrawingImage proprietà dell'oggetto DrawingImage.Drawing sul disegno che si desidera visualizzare.

Nell'esempio seguente viene utilizzato un DrawingImage controllo e Image per visualizzare un oggetto GeometryDrawing. Questo esempio produce il seguente output:

A GeometryDrawing of two ellipses
Oggetto DrawingImage

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SDKSample
{
    public class DrawingImageExample : Page
    {

        public DrawingImageExample()
        {

            //
            // Create the Geometry to draw.
            //
            GeometryGroup ellipses = new GeometryGroup();
            ellipses.Children.Add(
                new EllipseGeometry(new Point(50,50), 45, 20)
                );
            ellipses.Children.Add(
                new EllipseGeometry(new Point(50, 50), 20, 45)
                );

            //
            // Create a GeometryDrawing.
            //
            GeometryDrawing aGeometryDrawing = new GeometryDrawing();
            aGeometryDrawing.Geometry = ellipses;

            // Paint the drawing with a gradient.
            aGeometryDrawing.Brush =
                new LinearGradientBrush(
                    Colors.Blue,
                    Color.FromRgb(204,204,255),
                    new Point(0,0),
                    new Point(1,1));

            // Outline the drawing with a solid color.
            aGeometryDrawing.Pen = new Pen(Brushes.Black, 10);

            //
            // Use a DrawingImage and an Image control
            // to display the drawing.
            //
            DrawingImage geometryImage = new DrawingImage(aGeometryDrawing);

            // Freeze the DrawingImage for performance benefits.
            geometryImage.Freeze();

            Image anImage = new Image();
            anImage.Source = geometryImage;
            anImage.HorizontalAlignment = HorizontalAlignment.Left;

            //
            // Place the image inside a border and
            // add it to the page.
            //
            Border exampleBorder = new Border();
            exampleBorder.Child = anImage;
            exampleBorder.BorderBrush = Brushes.Gray;
            exampleBorder.BorderThickness = new Thickness(1);
            exampleBorder.HorizontalAlignment = HorizontalAlignment.Left;
            exampleBorder.VerticalAlignment = VerticalAlignment.Top;
            exampleBorder.Margin = new Thickness(10);

            this.Margin = new Thickness(20);
            this.Background = Brushes.White;
            this.Content = exampleBorder;
        }
    }
}
<Page 
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:PresentationOptions="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options" 
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  mc:Ignorable="PresentationOptions"
  Background="White" Margin="20">

  <Border BorderBrush="Gray" BorderThickness="1" 
    HorizontalAlignment="Left" VerticalAlignment="Top"
    Margin="10">

    <!-- This image uses a Drawing object for its source. -->
    <Image>
      <Image.Source>
        <DrawingImage PresentationOptions:Freeze="True">
          <DrawingImage.Drawing>
            <GeometryDrawing>
              <GeometryDrawing.Geometry>
                <GeometryGroup>
                  <EllipseGeometry Center="50,50" RadiusX="45" RadiusY="20" />
                  <EllipseGeometry Center="50,50" RadiusX="20" RadiusY="45" />
                </GeometryGroup>
              </GeometryDrawing.Geometry>
              <GeometryDrawing.Brush>
                <LinearGradientBrush>
                  <GradientStop Offset="0.0" Color="Blue" />
                  <GradientStop Offset="1.0" Color="#CCCCFF" />
                </LinearGradientBrush>
              </GeometryDrawing.Brush>
              <GeometryDrawing.Pen>
                <Pen Thickness="10" Brush="Black" />
              </GeometryDrawing.Pen>
            </GeometryDrawing>
          </DrawingImage.Drawing>
        </DrawingImage>
      </Image.Source>
    </Image>
  </Border>

</Page>

Disegnare un oggetto con un oggetto

Un DrawingBrush oggetto è un tipo di pennello che disegna un'area con un oggetto disegno. Può essere usato per disegnare quasi tutti gli oggetti grafici con un oggetto Drawing. La Drawing proprietà di un DrawingBrush oggetto descrive il relativo Drawingoggetto . Per eseguire il rendering di un Drawing oggetto con un DrawingBrushoggetto , aggiungerlo al pennello usando la proprietà del Drawing pennello e usare il pennello per disegnare un oggetto grafico, ad esempio un controllo o un pannello.

Negli esempi seguenti viene utilizzato un DrawingBrush oggetto per disegnare un RectangleFill oggetto con un motivo creato da un oggetto GeometryDrawing. Questo esempio produce il seguente output:

A tiled DrawingBrush
Oggetto GeometryDrawing usato con un oggetto DrawingBrush

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SDKSample
{
    public class DrawingBrushExample : Page
    {

        public DrawingBrushExample()
        {

            //
            // Create the Geometry to draw.
            //
            GeometryGroup ellipses = new GeometryGroup();
            ellipses.Children.Add(
                new EllipseGeometry(new Point(50,50), 45, 20)
                );
            ellipses.Children.Add(
                new EllipseGeometry(new Point(50, 50), 20, 45)
                );

            //
            // Create a GeometryDrawing.
            //
            GeometryDrawing aGeometryDrawing = new GeometryDrawing();
            aGeometryDrawing.Geometry = ellipses;

            // Paint the drawing with a gradient.
            aGeometryDrawing.Brush =
                new LinearGradientBrush(
                    Colors.Blue,
                    Color.FromRgb(204,204,255),
                    new Point(0,0),
                    new Point(1,1));

            // Outline the drawing with a solid color.
            aGeometryDrawing.Pen = new Pen(Brushes.Black, 10);

            DrawingBrush patternBrush = new DrawingBrush(aGeometryDrawing);
            patternBrush.Viewport = new Rect(0, 0, 0.25, 0.25);
            patternBrush.TileMode = TileMode.Tile;
            patternBrush.Freeze();

            //
            // Create an object to paint.
            //
            Rectangle paintedRectangle = new Rectangle();
            paintedRectangle.Width = 100;
            paintedRectangle.Height = 100;
            paintedRectangle.Fill = patternBrush;

            //
            // Place the image inside a border and
            // add it to the page.
            //
            Border exampleBorder = new Border();
            exampleBorder.Child = paintedRectangle;
            exampleBorder.BorderBrush = Brushes.Gray;
            exampleBorder.BorderThickness = new Thickness(1);
            exampleBorder.HorizontalAlignment = HorizontalAlignment.Left;
            exampleBorder.VerticalAlignment = VerticalAlignment.Top;
            exampleBorder.Margin = new Thickness(10);

            this.Margin = new Thickness(20);
            this.Background = Brushes.White;
            this.Content = exampleBorder;
        }
    }
}
<Page 
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:PresentationOptions="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options" 
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  mc:Ignorable="PresentationOptions"
  Margin="20" Background="White">

  <Border BorderBrush="Gray" BorderThickness="1" 
    HorizontalAlignment="Left" VerticalAlignment="Top"
    Margin="10">
    <Rectangle Width="100" Height="100">
      <Rectangle.Fill>
        <DrawingBrush PresentationOptions:Freeze="True"
                      Viewport="0,0,0.25,0.25" TileMode="Tile">
          <DrawingBrush.Drawing>
            <GeometryDrawing>
              <GeometryDrawing.Geometry>
                <GeometryGroup>
                  <EllipseGeometry Center="50,50" RadiusX="45" RadiusY="20" />
                  <EllipseGeometry Center="50,50" RadiusX="20" RadiusY="45" />
                </GeometryGroup>
              </GeometryDrawing.Geometry>
              <GeometryDrawing.Brush>
                <LinearGradientBrush>
                  <GradientStop Offset="0.0" Color="Blue" />
                  <GradientStop Offset="1.0" Color="#CCCCFF" />
                </LinearGradientBrush>
              </GeometryDrawing.Brush>
              <GeometryDrawing.Pen>
                <Pen Thickness="10" Brush="Black" />
              </GeometryDrawing.Pen>
            </GeometryDrawing>
          </DrawingBrush.Drawing>
        </DrawingBrush>
      </Rectangle.Fill>

    </Rectangle>
  </Border>


</Page>

La DrawingBrush classe offre un'ampia gamma di opzioni per l'estensione e l'associazione del contenuto. Per altre informazioni su DrawingBrush, vedere la panoramica Disegnare con immagini, disegni e oggetti visivi.

Eseguire il rendering di un disegno con un oggetto Visual

Un DrawingVisual oggetto è un tipo di oggetto visivo progettato per eseguire il rendering di un disegno. Lavorare direttamente a livello visivo è un'opportunità per gli sviluppatori che desiderano creare un ambiente grafico altamente personalizzato, ma questo argomento non viene descritto in questa panoramica. Per altre informazioni, vedere Utilizzo degli oggetti DrawingVisual.

Oggetti DrawingContext

La DrawingContext classe consente di popolare un Visual oggetto o con Drawing contenuto visivo. Molti oggetti grafici di basso livello utilizzano un oggetto DrawingContext perché descrive in modo molto efficiente il contenuto grafico.

Anche se i DrawingContext metodi di disegno appaiono simili ai metodi di disegno del System.Drawing.Graphics tipo, sono in realtà molto diversi. DrawingContext viene utilizzato con un sistema grafico in modalità mantenuta, mentre il System.Drawing.Graphics tipo viene usato con un sistema grafico in modalità immediata. Quando si usano i comandi di disegno di un DrawingContext oggetto, si archivia effettivamente un set di istruzioni di rendering (anche se il meccanismo di archiviazione esatto dipende dal tipo di oggetto che fornisce ) DrawingContextche verrà usato successivamente dal sistema grafico; non si sta disegnando sullo schermo in tempo reale. Per altre informazioni sul funzionamento del sistema grafico Windows Presentation Foundation (WPF), vedere Cenni preliminari sul rendering della grafica WPF.

Non creare mai direttamente un'istanza DrawingContextdi . È tuttavia possibile acquisire un contesto di disegno da determinati metodi, ad esempio DrawingGroup.Open e DrawingVisual.RenderOpen.

Enumerare il contenuto di un oggetto Visual

Oltre agli altri usi, Drawing gli oggetti forniscono anche un modello a oggetti per enumerare il contenuto di un oggetto Visual.

Nell'esempio seguente viene utilizzato il GetDrawing metodo per recuperare il DrawingGroup valore di un Visual oggetto ed enumerarlo.

public void RetrieveDrawing(Visual v)
{
    DrawingGroup drawingGroup = VisualTreeHelper.GetDrawing(v);
    EnumDrawingGroup(drawingGroup);
}

// Enumerate the drawings in the DrawingGroup.
public void EnumDrawingGroup(DrawingGroup drawingGroup)
{
    DrawingCollection dc = drawingGroup.Children;

    // Enumerate the drawings in the DrawingCollection.
    foreach (Drawing drawing in dc)
    {
        // If the drawing is a DrawingGroup, call the function recursively.
        if (drawing is DrawingGroup group)
        {
            EnumDrawingGroup(group);
        }
        else if (drawing is GeometryDrawing)
        {
            // Perform action based on drawing type.
        }
        else if (drawing is ImageDrawing)
        {
            // Perform action based on drawing type.
        }
        else if (drawing is GlyphRunDrawing)
        {
            // Perform action based on drawing type.
        }
        else if (drawing is VideoDrawing)
        {
            // Perform action based on drawing type.
        }
    }
}

Vedi anche