Domanda

Ho sottoclasse Canvas modo che io possa ignorare la sua funzione Render. Ho bisogno di sapere come posso caricare una bitmap in WPF e rendere che alla tela. Sono completamente nuovo per WPF e non ho trovato alcun tutorial che mostrano come fare qualcosa di così apparentemente banale. Step-by-passo le istruzioni con esempi sarebbe grande.

È stato utile?

Soluzione

Questo dovrebbe iniziare:

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));
   }
}

Altri suggerimenti

In WPF si tratta di un caso raro che si avrebbe bisogno di ignorare OnRender soprattutto se tutto quello che voleva fare era disegnare un BMP a uno sfondo:

<Canvas>
    <Canvas.Background>
        <ImageBrush ImageSource="Resources\background.bmp" />
    </Canvas.Background>
    <!-- ... -->
</Canvas>

Se non vuole dipingere sfondo di tela, mi consiglia di utilizzare ImageBrush come Background, 'coz questo è semplice come non avete bisogno di sottoclasse Canvas a esclusione Onender.

Ma io ti do un codice sorgente demo per quello che avete chiesto:

Creare una classe (l'ho chiamata 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);
            }
        }
    }

Ora è possibile utilizzare in questo modo:

<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>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top