Search code examples
c#xamarinportable-class-library

Xamarin native apps + PCL: Share images in PCL project


I'm developing an app for multiple platforms using Xamarin. Shared code is hosted in a separate PCL project. The project contains a large collection of images, which I would also like to share via the PCL project.

Is that possible? How can I access the image data from my platform-specific projects?


Solution

  • What I finally did (until now, I could only verify on an iOS and Droid project, Windows Phone is still in the works):

    I return the image data from my shared project as Stream, as in:

    public Stream GetImageStream () {
        return assembly.GetManifestResourceStream (nameOfResource);
    }
    

    Images' properties are set to EmbeddedResource. In my iOS project, I can then access my image like so:

    using (var stream = myClass.GetImageStream ()) {
        var image = new UIImage (NSData.FromStream (stream));
        // do stuff with image
    }
    

    And on Android I use the following code:

    using (var stream = myClass.GetImageStream ()) {
        var bitmap = BitmapFactory.DecodeStream (stream);
        // do stuff with bitmap
    }
    

    Feedback whether there any gotchas with this practice are welcome! (beside the obvious sizing-issue, which I can live with for now, I could imagine that this approach circumvents any platform-specific caching mechanisms?)