Search code examples
c#xamarin.formsxamarin.androidxamarin.ioscustom-renderer

How to get the image width of the button image in a custom renderer?


I need to get the actual size of the image in my button renderer class. I need to get it in the OnElementChanged method from the variable e.NewElement.

I have tried to get it from e.NewElement.ImageSource, but it does not have a property width or size. If I debug it, the size is shown.

protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
        {
            base.OnElementChanged(e);
           //How to get width here from e ? 
}

Solution

  • You need to look for the native counter-part, in Android like below:

    protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
    {
                base.OnElementChanged(e);
                var image = Control?.GetCompoundDrawables()[0];
                if (image != null)
                    //image.IntrinsicWidth
    }
    

    In iOS something like:

    protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
    {
                base.OnElementChanged(e);
                var image = Control?.CurrentImage;
                if (image != null)
                    //image.Size.Width
    }