jamesmontemagno / ImageCirclePlugin

Circle Images for your Xamarin.Forms Applications
MIT License
240 stars 68 forks source link

[UWP] Issue without HeightRequest/WidthRequest and with using scaled image files #27

Closed kp-xcess closed 5 years ago

kp-xcess commented 7 years ago

The renderer on UWP (which apparently is refering to the WinRT-implementation) will currently not work if no specific width and height are requested from within XF.

Element.Width and Element.Height are then both set to 0 within the renderer on UWP and so you need to determine the image's dimensions manually before you can start initialising the resulting Ellipse.

Another issue is with using scaled images. Your current implementation literally attempts to open the file by it's given filename, which will not work when trying to refer to a scaled image.

I solved both these issues like following:

if (this.Element.Source is FileImageSource)
{
    // Allow using scaled images by prefixing the given filename with "ms-appx:///".
    fileUri = new Uri(String.Concat("ms-appx:///", ((FileImageSource) this.Element.Source).File));
}
else if (this.Element.Source is UriImageSource)
{
    fileUri = ((UriImageSource) this.Element.Source).Uri;
}

double elementWidth = this.Element.WidthRequest;
double elementHeight = this.Element.HeightRequest;

if (elementWidth.Equals(-1) && elementHeight.Equals(-1))
{
    StorageFile sf = await StorageFile.GetFileFromApplicationUriAsync(fileUri);
    BitmapDecoder dec = await BitmapDecoder.CreateAsync(await sf.OpenAsync(FileAccessMode.Read));

    elementWidth = dec.PixelWidth;
    elementHeight = dec.PixelHeight;

    this.Element.WidthRequest = elementWidth;
    this.Element.HeightRequest = elementHeight;
}

For determining the correct dimensions for the given image, in case they are not requested from XF, I am instantiating a StorageFile instance and passing it the proper Uri. Using the BitmapDecoder we can get various image properties, including it's width and height, from that StorageFile.

Note that I haven't actually tested this with a UriImageSource yet, and I haven't implemented the workaround for StreamImageSource. This should however at least point you in the right direction for a proper fix :)