1. OnRender doesn't render in the code 1 because the visual
MyImage is not added into a visual tree. But it renders when you add it into the visual tree of
Canvas.
Source:
WPF: InvalidateVisual doesn't draw by OnRender.[
^]
2. Even if it renders on the surface of
Canvas, it will not render into
ImageBrush because the brush is for raster based images, but not for vector based images. That is why it renders a raster image when you add it via a link.
3. You should use
VisualBrush[
^] as it is for vector based images.
4.
VisualCollection/
DrawingVisual in the code 2 renders even if you don't add
MyImage into the visual tree of
Canvas.
Code:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Canvas canvas = new Canvas();
this.Content = canvas;
canvas.Background = Brushes.Black;
MyImage myimage = new MyImage();
VisualBrush visualbrush = new VisualBrush();
visualbrush.Visual = myimage;
canvas.Background = visualbrush;
}
}
class MyImage : Image
{
public MyImage()
{
visuals = new VisualCollection(this);
visual = new DrawingVisual();
visuals.Add(visual);
Draw();
}
private void Draw()
{
using (DrawingContext dc = visual.RenderOpen())
dc.DrawRectangle(Brushes.Red, null, new Rect(0, 0, 100, 100));
}
VisualCollection visuals;
DrawingVisual visual;
protected override Visual GetVisualChild(int index)
{
return visuals[index];
}
protected override int VisualChildrenCount
{
get { return visuals.Count; }
}
}