Search code examples
bitmapxamarin.formsicons

how to use Bitmap for Xamarin.Forms?


How can I use bitmap from Xamarin Forms? This is used to be on my Android project, but I would like to use something like this from Xamarin Forms. I don't want to do any renders or platform specific. If I can just do it in Forms will be great. Any idea?

review forms :

     private async void GetIcon()
        {
            Weather weather = await Core.GetWeather();

            var bitmap = new Image { Source = ImageSource.FromUri(new Uri("http://openweathermap.org/img/w/" + weather.Icon + ".png")) };

DisplayIcon.bitmap ?

        }

xaml :

 <Image x:Name="DisplayIcon" Source ="{Binding bitmap}" />

ends here *******

****old post****

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;
        }

        private async void displayIcon()
        {
            Weather weather = await Core.GetWeather();
            if (weather != null)
            {

                var bitmap = GetImageBitmapFromUrl("http://openweathermap.org/img/w/" + weather.Icon + ".png");
                Icon2.SetImageBitmap(bitmap);

            }
        }

Solution

  • For some reason binding the Image didn't work as I expected. However, I found this workaround as a solution.

    I add this to C#

    var bitmap = new Image { Source = ImageSource.FromUri(new Uri("http://openweathermap.org/img/w/" + weather.Icon + ".png")) };
    
                DisplayIcon.Source = bitmap.Source;
    

    and this to XAML

    <Image x:Name="DisplayIcon"/>
    

    Thank you all for your answers .