0

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.

1 Answers1

0

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.

Filip Skakun
  • 31,624
  • 6
  • 74
  • 100
  • Hi, Sorry for the late answer! You're answer do the trick but does not work with transparent image. It is a WriteableBitmap problem, BitmapImage works... Anyway I've solved splitting the original image. WriteableBitmap does not recognize Transparency, BitmapImage does not crop and load only after the Image element is displayed, load image using stream is an async method while I need a synch one... For example i cannot know BitmapImage size (in pixel) until Image show up. In WPF was really simpler and more elegant – Alberto Nuti May 23 '14 at 08:59