10

我已经进行了子类化Canvas,以便我可以覆盖它的Render功能。我需要知道如何在 WPF 中加载位图并将其渲染到画布上。我对 WPF 完全陌生,我还没有找到任何教程来告诉你如何做一些看似微不足道的事情。带有示例的分步说明会很棒。

4

3 回答 3

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>
于 2010-01-30T16:12:40.293 回答
11

这应该让你开始:

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));
   }
}
于 2010-01-30T15:45:13.490 回答
3

如果您确实想绘制画布的背景,我建议您使用ImageBrushas Background,'因为这很简单,因为您不需要子类Canvas来覆盖Onender

但我会给你一个演示源代码来满足你的要求:

创建一个类(我称之为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);
            }
        }
    }

现在你可以像这样使用它:

<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>
于 2010-01-30T16:06:17.813 回答