问题描述
目标:通过VisualCollection在Canvas上绘制。
问题:它使用Window。
问题:如何解决? Visual Parent的含义是什么?
描述:我通过Canvas实例创建一个VisualCollection实例作为Visual Parent,但它在Window上绘制,尽管我从未将它作为内容添加到Window。
那么,如果它仍然使用Window,Visual Parent意味着什么?换句话说,我想在图像或画布上绘制并保存它,但不是在窗口上,我不想显示我绘制的内容。
代码:
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:
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; }
}
}
推荐答案
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);
}
}
这篇关于如何通过VisualCollection在Canvas上绘制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!