C# 如何在 WPF 中将位图渲染到画布中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2168370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to render bitmap into canvas in WPF?
提问by void.pointer
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'm completely new to WPF and I haven't found any tutorials that show you how to do something so seemingly trivial. Step-by-step instructions with examples would be great.
我已经子类化,Canvas
以便我可以覆盖它的Render
功能。我需要知道如何在 WPF 中加载位图并将其渲染到画布上。我对 WPF 完全陌生,我还没有找到任何教程来向您展示如何做一些看似微不足道的事情。带有示例的分步说明会很棒。
采纳答案by Tarydon
This should get you started:
这应该让你开始:
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));
}
}
回答by mg007
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
.
如果您确实想绘制画布背景,我建议使用ImageBrush
as Background
,'因为这很简单,因为您不需要子类Canvas
来覆盖Onender
.
But I'll give you a demo source-code for what you have asked:
但我会给你一个演示源代码,用于你所问的问题:
Create a class (I've called it ImageCanvas
)
创建一个类(我称之为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:
现在你可以像这样使用它:
<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>
回答by user7116
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:
在 WPF 中,您需要覆盖的情况很少见,OnRender
特别是如果您只想将 BMP 绘制到背景:
<Canvas>
<Canvas.Background>
<ImageBrush ImageSource="Resources\background.bmp" />
</Canvas.Background>
<!-- ... -->
</Canvas>