将位图放置在C# [英] Placing Bitmap in Canvas in C#
问题描述
我想要的是简单的。我想把 BitmapImage
放入C#中的 Canvas
中。我的应用程序是基于WPF。我搜索这个,我发现了类似的问题,但我找不到我要找的。 p>
总之,我有这个:
BitmapImage img = new BitmapImage(new Uri(c:\\xyz.jpg));
我想把这个放在画布上,意思不是那么重要,矩形等。
A BitmapImage
Canvas
,因为它不是控件。你可以做的是从 Canvas
中导出自己的类,并覆盖 OnRender()
方法来绘制位图。基本上像这样:
class CanvasWithBitmap:Canvas
{
public CanvasWithBitmap()
{
_image = new BitmapImage(new Uri(@c:\xyz.jpg));
}
protected override void OnRender(DrawingContext dc)
{
dc.DrawImage(_image,
new Rect(0,0,_image.PixelWidth ,_image.PixelHeight));
}
private BitmapImage _image;
}
当然,您可能需要公开文件路径和< c $ c> Canvas 通过属性。如果你不想声明自己的类只是为了绘制位图,那么你不能直接使用 BitmapImage
类。显示图片的控制是 Image
,让我们尝试这样:
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(@c:\xyz.jpg);
bitmap.EndInit();
Image image = new Image();
image.Source = bitmap;
现在你可以把 Image
你想在 Canvas
里面。
Possible Duplicate:
How to render bitmap into canvas in WPF?
What I want is simple. I want to place a BitmapImage
into a Canvas
in C#. My app is based on WPF. I searched for this and I found similar questions, but I could not find what I'm looking for.
In short, I have this:
BitmapImage img = new BitmapImage(new Uri("c:\\xyz.jpg"));
And I want to put this in the canvas, the mean is not that important, it can be a rectangle or whatever.
A BitmapImage
object cannot be positioned inside a Canvas
because it's not a control. What you can do is to derive your own class from the Canvas
and override the OnRender()
method to draw your bitmap. Basically something like this:
class CanvasWithBitmap : Canvas
{
public CanvasWithBitmap()
{
_image = new BitmapImage(new Uri(@"c:\xyz.jpg"));
}
protected override void OnRender(DrawingContext dc)
{
dc.DrawImage(_image,
new Rect(0, 0, _image.PixelWidth, _image.PixelHeight));
}
private BitmapImage _image;
}
Of course you may need to expose the file path and coordinates inside the Canvas
through properties. If you do not want to declare your own class just to draw a bitmap then you can't use the BitmapImage
class directly. The control to display images is Image
, let's try this:
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(@"c:\xyz.jpg");
bitmap.EndInit();
Image image = new Image();
image.Source = bitmap;
Now you can put the Image
control where you want inside the Canvas
.
这篇关于将位图放置在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!