Search code examples
androidxamarin.formsuwpskshapenode

SKSharp not loading Bitmap Xamarin Forms


I'm trying to load "png's" into a ListView in a XamarinForms app using Android and UWP projects.

Here is my xaml of the ListView.

   <ListView x:Name="TemplateListView"
        ItemsSource="{Binding TemplateData}">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <StackLayout Orientation="Vertical">
                                    <Image Margin="20,0,0,0" Source="{Binding ImageData}" Aspect="AspectFit" HeightRequest="120"></Image>
                                    <Label Text="{Binding Title}"  FontSize="16" />
                                </StackLayout>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>

My object class is a very simple one.

public class TemplateData
{
    public string Title { get; set; }
    public SKBitmap ImageData { get; set; }
}

And here is the SKSharp code to load the bitmaps and assign to the collection as the ListViews ItemSource.

//load the image and assisgn it as an Item
     this.TemplateListView.ItemsSource = new TemplateData[]
 {
               new TemplateData{Title="A", ImageData=LoadImage("A.jpg")},
               new TemplateData{Title="B", ImageData=LoadImage("B.jpg")},
          
 };

// for this code image needs to be a project resource

    private SKBitmap LoadImage(string filename)
    {
      //  string resourceID = filename;
        string resourceID = "CWON_App.Images."+filename;
        Assembly assembly = GetType().GetTypeInfo().Assembly;

        using (Stream stream = assembly.GetManifestResourceStream(resourceID))
        {
            resourceBitmap = SKBitmap.Decode(stream);
        }

        return resourceBitmap;

    }

My images are in the Images folder of the UWP project and marked as Embedded Resource.

The app runs with no errors but nothing is displayed in the ListView.


Solution

  • Xamarin image control can't load SKBitmap, for this scenario we suggest you use ImageSource to replace SKBitmap.

    If you have place the image in the uwp project folder, you could use ImageSource.FromFile method to load image, and please note the image build action need to be Content.

    private ImageSource LoadImage(string filename)
    {
        var source = Device.RuntimePlatform == Device.UWP ? ImageSource.FromFile($"Assets/{filename}") : ImageSource.FromFile("waterfront.jpg");
        return source;
    }
    

    For more please refer Xamarin Working with image.