如何呈现位图到WPF画布?
-
24-09-2019 - |
题
我子类Canvas
这样我可以覆盖其Render
功能。我需要知道我可以加载在WPF位图,渲染到画布上。我完全新的WPF,我还没有发现,告诉你如何做这样看似琐碎的任何教程。一步步骤与实施例说明将是巨大的。
解决方案
这应该让你开始:
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));
}
}
其他提示
在WPF它是一种罕见的情况下,你会需要重写OnRender
特别是如果你想要做的一切都画一个BMP的背景:
<Canvas>
<Canvas.Background>
<ImageBrush ImageSource="Resources\background.bmp" />
</Canvas.Background>
<!-- ... -->
</Canvas>
如果你想画的画布的背景下,我会建议使用ImageBrush
作为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>
不隶属于 StackOverflow