The World’s Leading Microsoft .NET Magazine
   
 
timstall

Donate Today!

Search Box

 

Calendar

««Mar 2010»»
SMTWTFS
  12
3
456
7
8
9
10
111213
14151617181920
21222324252627
28293031

My RSS Feeds








Mailing List

Most Popular Tags

                                                           

Dynamically load an image in Silverlight 2.0 Beta

posted Saturday, 15 March 2008
You can easily dynamically load images in Silverlight. given a relative url, you can convert that to an absolute url, and then to an ImageSource, and then use that to set an image. Here's a sample method that takes the relative path, the parent canvas that we'll add the image too, and an x-y point:

 

    private void AddImage(string strRelativeImagePath, Canvas myCanvas, Point p)
    {
      //Convert from RelativePath to AbsolutePath to Uri to ImageSource
      string strFullUrl = GetAbsoluteUrl(strRelativeImagePath);
      Uri u = new Uri(strFullUrl, UriKind.Absolute);
      System.Windows.Media.Imaging.BitmapImage b = new System.Windows.Media.Imaging.BitmapImage(u);

      //Create the image here
      Image img = new Image();
      img.Source = b;
      img.SetValue(Canvas.LeftProperty, p.X);
      img.SetValue(Canvas.TopProperty, p.Y);
      //set other properties here...

      //now add to a canvas:
      myCanvas.Children.Add(img);
    }

 

And just call it like so:

 

    AddImage("MyImage.png", this.parentCanvas, new Point(100, 50));

 

Note some changes from the 1.1 Alpha:

  • Image.Source is no longer just a string url, but rather a strongly-typed class. You need to create an ImageSource object first, such as by instantiating a Bitmap image (this allows other image types, like png, not just bmp).

  • The relative-to directory has changed, such that it's easiest to just convert to an absolute url. When you directly add this to the page, it works fine, but if you add it to a userControl from another class library, then it doesn't. Just using absolute urls makes it work (hence the GetAbsoluteUrl method I blogged about yesterday).

tags:  

links: digg this    technorati    




1. maya left...
Thursday, 8 May 2008 1:26 pm

Silverlight 2 beta 1 doesn't support Gif and bmp images ,only supports png and jpg, so if anyone has a solution to this problem other than renaming the images please specify Note: am still a Silverlight beginner so please explain your answer in details


2. Tim Stall left...
Friday, 9 May 2008 9:25 pm

To my knowledge, they don't yet support Gif because they didn't want to deal with animated Gif, and they don't support bitmaps because those are huge (compared to a gif/png/jpg) and would be impractical to download.