Click here to Skip to main content
15,847,427 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Goal: To draw on Canvas by VisualCollection.
Problem: It draws on Window.
Question: How to solve? What does Visual Parent means?
Description: I create a VisualCollection instance by a Canvas instance as Visual Parent, but it draws on Window despite the fact i never added it to Window as content.
So what does Visual Parent means if it still draws on Window? In other words i wanna draw on Image or Canvas and save it, but not on Window, i don't wanna show what i draw.
Code:
C#
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        Canvas canvas = new Canvas();
        vc = new VisualCollection(canvas);
        this.Loaded += MainWindow_Loaded;
    }

    VisualCollection vc;

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        DrawingVisual dv = new DrawingVisual();
        DrawingContext dc = dv.RenderOpen();

        dc.DrawRectangle(Brushes.Red, new Pen(Brushes.Red, 5), new Rect(10, 10, 100, 100));
        dc.Close();

        vc.Add(dv);
    }

    protected override Visual GetVisualChild(int index)
    {
        return vc[index];
    }
    protected override int VisualChildrenCount
    {
        get { return vc.Count; }
    }
}
Posted
Updated 2-Jun-15 23:31pm
v5

1 solution

Solved!
Next code draws on Image and adds Image to Canvas without VisualCollection:
C#
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        canvas = new Canvas();
        canvas.Width = 300;
        canvas.Height = 300;
        this.Content = canvas;
        this.Loaded += MainWindow_Loaded;
    }

    Canvas canvas;

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        DrawingVisual dv = new DrawingVisual();
        DrawingContext dc = dv.RenderOpen();

        dc.DrawRectangle(Brushes.Red, new Pen(Brushes.Red, 5), new Rect(10, 10, 100, 100));
        dc.Close();

        RenderTargetBitmap bmp = new RenderTargetBitmap(180, 180, 0, 0, PixelFormats.Pbgra32);
        bmp.Render(dv);

        Image image = new Image();
        image.Source = bmp;

        canvas.Children.Add(image);
    }
}
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900