Sunday, April 28, 2013

Xamarin Tip: Loading an Image


You have some images in your application bundle and want to display one of the images in your application UI.

Assuming you have the Images folder within the Resources folder. Within the Images folder, you have an image named “A Good Day to Die Hard.jpg”. You can load an UIImageView view with the following method:

    this.imageView.Image = 
        UIImage.FromFile("Images/A Good Day to Die Hard.jpg");
The UIImage.FromFile() method loads the image asynchronously. It also allows the application to load the image from an external location.

Alternatively, you can also use the UIImage.FromBundle() method to load the image:

this.imageView.Image = 
    UIImage.FromBundle("Images/A Good Day to Die Hard.jpg");

Unlike the UIImage.FromFile() method, the UIImage.FromBundle() method is a blocking call and only loads images from within the application bundle. However, it caches the images aftre loading it. In general, use the UIImage.FromBundle() method if you need to frequently load the same image. Otherwise, use the UIImage.FromFile() method as it is asynchronous and will not block your UI. 

No comments: