Search code examples
c#microsoft-metrobitmapimagewriteablebitmap

BitmapImage METRO re-use WPF code


I have written a little game using IronPython and WPF for didactic purpose and now I want to translate the project to Metro APP for test Shared Projects.

The guilty code is:

def LoadImage(name, sourceRect):
    bmp = BitmapImage()
    bmp.BeginInit()
    bmp.UriSource = Uri("./data/images/" + name, UriKind.Relative)
    bmp.SourceRect = sourceRect
    bmp.EndInit()
    image = Image()
    image.Source = bmp
    return image

How on the earth I can obtain the same result in a Metro app (using C#)? There must be a way to do this in a simple manner like old BitmapImage. I need this because I have tiled images and I want a portion of it to display. WriteableBitmap work but ignore transparency of the image, so it's useless.


Solution

  • I've been using this code to load an image scaled:

        public static async Task SetSourceAsync(
            this WriteableBitmap writeableBitmap,
            IRandomAccessStream streamSource,
            uint decodePixelWidth,
            uint decodePixelHeight)
        {
            var decoder = await BitmapDecoder.CreateAsync(streamSource);
    
            using (var inMemoryStream = new InMemoryRandomAccessStream())
            {
                var encoder = await BitmapEncoder.CreateForTranscodingAsync(inMemoryStream, decoder);
                encoder.BitmapTransform.ScaledWidth = decodePixelWidth;
                encoder.BitmapTransform.ScaledHeight = decodePixelHeight;
                await encoder.FlushAsync();
                inMemoryStream.Seek(0);
    
                await writeableBitmap.SetSourceAsync(inMemoryStream);
            }
        }
    

    You might use something similar, but you'd specify encoder.BitmapTransform.Bounds instead of ScaledWidth/Height to do the cropping. If you have more specific questions - please clarify.