Femil Shajin
Femil Shajin

Reputation: 1808

How to display an image from URL in imagebutton - xamarin Android

I am a newbie in Xamarin. I have been trying to set an image to Imagebutton from specific a URL in C# for Xamarin. I googled and was unable to find a sample code or documentation. It would be helpful if any one provide me with a helpful documentation or a little bit of sample code to do this.

Thanks In Advance... :)

Upvotes: 2

Views: 5025

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222722

To set the ‘default’ image for a button from local images, call SetImage

button1 = UIButton.FromType(UIButtonType.RoundedRect);
button1.SetImage(UIImage.FromFile ("sample.png"), UIControlState.Normal);

To apply from an URL,

button1  = FindViewById(Resource.Id.RoundedRect);
var imageBitmap = GetImageBitmapFromUrl("http://xamarin.com/resources/design/home/test.png");
button1.SetImageBitmap(imageBitmap);


private Bitmap GetImageBitmapFromUrl(string url)
{
     Bitmap imageBitmap = null;

     using (var webClient = new WebClient())
     {
          var imageBytes = webClient.DownloadData(url);
          if (imageBytes != null && imageBytes.Length > 0)
          {
               imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
          }
     }

     return imageBitmap;
}

Upvotes: 3

Related Questions