Tuesday, May 6, 2014

Copying a project resource image to a WriteableBitmap in a Windows Store application

It seems like the Windows Store application projects in Visual Studio 2013 Update 2 do not like embedded resources:

Build action 'EmbeddedResource' is not supported by projects with an output type of 'appcontainerexe'.

So far I have used embedded resources to include image files that I programmatically assign to WriteableBitmap objects for example in my Windows Store applications, but now this approach does not seem so fruitful any longer.

Here is what I did instead.

a) Set the image file Build Action to Content, and Copy Always to Output Directory:


b) Reference the WriteableBitmapEx library, most easily via NuGet.

c) Use the FromContent extension method in the WriteableBitmapEx library to load the image via its URI:

var tmp = BitmapFactory.New(1, 1);
var wbm = await tmp.FromContent(
    new Uri("ms-appx:///Assets/image.jpg"));

And voilá! Now the image file resource is sufficiently loaded into wbm.

BitmapFactory.New is a method in WriteableBitmapEx which can be used portably to create a WriteableBitmap object across different targets such as Windows Store, Windows Phone, .NET Framework etc.

Otherwise, practically all methods in WriteableBitmapEx are extension methods, and therefore the FromContent method a little awkwardly requires an incoming WriteableBitmap object, that it ignores.

ms-appx:/// is the root or base URI (Uniform Resource Identifier) of the application, and Assets/image.jpg is the path relative to the base URI.

No comments:

Post a Comment