Ho creato una sottoclasse di Canvas
in modo da poter ignorare la sua funzione Render
. Ho bisogno di sapere come posso caricare una bitmap in WPF e renderla sul canvas. Sono completamente nuovo a WPF e non ho trovato nessun tutorial che ti mostri come fare qualcosa di così apparentemente banale. Le istruzioni passo-passo con gli esempi sarebbero grandiose.Come rendere bitmap su tela in WPF?
9
A
risposta
11
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));
}
}
3
Se vuole dipingere sfondo di tela, mi consiglia di utilizzare ImageBrush
come Background
, 'coz questo è semplice come non avete bisogno di sottoclasse Canvas
per ignorare 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>
11
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>