Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display a DrawingVisual on Canvas

I have a drawing visual which I have drawings, how do I add this to my canvas and display?

 DrawingVisual drawingVisual = new DrawingVisual();

 // Retrieve the DrawingContext in order to create new drawing content.
 DrawingContext drawingContext = drawingVisual.RenderOpen();

 // Create a rectangle and draw it in the DrawingContext.
 Rect rect = new Rect(new System.Windows.Point(0, 0), new System.Windows.Size(100, 100));
 drawingContext.DrawRectangle(System.Windows.Media.Brushes.Aqua, (System.Windows.Media.Pen)null, rect);

 // Persist the drawing content.
 drawingContext.Close();

How do I add this to a canvas? Suppose I have a Canvas as

  Canvas canvas = null;
  canvas.Children.Add(drawingVisual); //Doesnt work as UIElement expected.

How do I add my drawingVisual to canvas?

TIA.

like image 649
Joga Avatar asked Mar 21 '16 08:03

Joga


People also ask

How do I add a drawing visual to my Canvas?

I have a drawing visual which I have drawings, how do I add this to my canvas and display? DrawingVisual drawingVisual = new DrawingVisual (); // Retrieve the DrawingContext in order to create new drawing content. DrawingContext drawingContext = drawingVisual.RenderOpen (); // Create a rectangle and draw it in the DrawingContext.

How do you display your canvas?

Here are seven ways to display your canvases in a stylish and secure manner. 1. Hidden Hooks The thickness of a canvas’ edges makes it tricky to frame.

What is the use of drawingvisual object?

DrawingVisual Object The DrawingVisualis a lightweight drawing class that is used to render shapes, images, or text. This class is considered lightweight because it does not provide layout or event handling, which improves its performance. For this reason, drawings are ideal for backgrounds and clip art.

What is the process of displaying an image on canvas?

The whole process of displaying/drawing an image on canvas can thus be summarised in just two steps: Selection and Drawing. Awesome! Not so complicated after all is it?


1 Answers

You have to implement a host element class, which would have to override the VisualChildrenCount property and the GetVisualChild() method of a derived UIElement or FrameworkElement to return your DrawingVisual.

The most basic implementation could look like this:

public class VisualHost : UIElement
{
    public Visual Visual { get; set; }

    protected override int VisualChildrenCount
    {
        get { return Visual != null ? 1 : 0; }
    }

    protected override Visual GetVisualChild(int index)
    {
        return Visual;
    }
}

Now you would add a Visual to your Canvas like this:

canvas.Children.Add(new VisualHost { Visual = drawingVisual });
like image 193
Clemens Avatar answered Sep 20 '22 04:09

Clemens