3

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.

Community
  • 1
  • 1
rooter
  • 173
  • 2
  • 3
  • 9
  • @mbeckish that one is irrelevant, i think. adding just a bitmap image should not be that complex, the guy proposes to extend canvas class. i am looking for an easier solution, since I am working on an already-written code and I do not want to make huge changes. – rooter Oct 12 '12 at 20:45
  • @rooter there is another answer for that question, it sets the bitmap as background for the Canvas. – Adriano Repetti Oct 12 '12 at 20:49
  • @rooter - Please add more specifics to your question so that we don't have to guess about what you would or would not find acceptable. – mbeckish Oct 12 '12 at 20:51
  • @Adriano that one also does not work, since I want to place it on a specific region, but not as a background picture. – rooter Oct 12 '12 at 20:52
  • add another canvas, place this one where you like in the canvas before and use the bitmap as background – oberfreak Oct 12 '12 at 20:59

1 Answers1

1

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.

Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208
  • It seems like deriving is the only solution. Thanks. – rooter Oct 12 '12 at 21:01
  • 1
    @rooter no, it's not. If you have a lot of Image controls (with the same image) you may consider to derive to save little bit of memory but you can always use the Image control. – Adriano Repetti Oct 12 '12 at 21:04