I've subclassed Canvas
so that I can override its Render
function. I need to know how I can load a bitmap in WPF and render that to the canvas. I'm completely new to WPF and I haven't found any tutorials that show you how to do something so seemingly trivial. Step-by-step instructions with examples would be great.
Asked
Active
Viewed 3.6k times
10

Dave Clemmer
- 3,741
- 12
- 49
- 72

void.pointer
- 24,859
- 31
- 132
- 243
3 Answers
15
In WPF it is a rare case that you would need to override OnRender
especially if all you wanted to do was draw a BMP to a background:
<Canvas>
<Canvas.Background>
<ImageBrush ImageSource="Resources\background.bmp" />
</Canvas.Background>
<!-- ... -->
</Canvas>

user7116
- 63,008
- 17
- 141
- 172
11
This should get you started:
class MyCanvas : Canvas {
protected override void OnRender (DrawingContext dc) {
BitmapImage img = new BitmapImage (new Uri ("c:\\demo.jpg"));
dc.DrawImage (img, new Rect (0, 0, img.PixelWidth, img.PixelHeight));
}
}

Tarydon
- 5,097
- 23
- 24
3
If you do want to paint background of canvas, I would recommend using ImageBrush
as Background
, 'coz that's simple as you dont need to subclass Canvas
to override Onender
.
But I'll give you a demo source-code for what you have asked:
Create a class (I've called it ImageCanvas
)
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace WpfApplication1
{
public class ImageCanvas : Canvas
{
public ImageSource CanvasImageSource
{
get { return (ImageSource)GetValue(CanvasImageSourceProperty); }
set { SetValue(CanvasImageSourceProperty, value); }
}
public static readonly DependencyProperty CanvasImageSourceProperty =
DependencyProperty.Register("CanvasImageSource", typeof(ImageSource),
typeof(ImageCanvas), new FrameworkPropertyMetadata(default(ImageSource)));
protected override void OnRender(System.Windows.Media.DrawingContext dc)
{
dc.DrawImage(CanvasImageSource, new Rect(this.RenderSize));
base.OnRender(dc);
}
}
}
Now you can use it like this:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1" Title="Window1" Height="300" Width="300">
<Grid>
<local:ImageCanvas CanvasImageSource="/Splash.png">
<TextBlock Text="Hello From Mihir!" />
</local:ImageCanvas>
</Grid>
</Window>

mg007
- 2,888
- 24
- 29
-
confused. how do I use this code? If I have a bitmap 'b', what do I do to render it? ` ImageCanvas.Render(b);` does not work. – john k Mar 11 '23 at 21:10