How to render bitmap into canvas in WPF?

前端 未结 3 642
日久生厌
日久生厌 2020-12-09 06:01

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\

3条回答
  •  庸人自扰
    2020-12-09 06:49

    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:

    
        
            
                
            
        
    
    

提交回复
热议问题