Custom ImageRenderer unable to get bitmap

Hi all,

I am trying to create a custom image render for android. Idea is to crop image based on the Image control size.

This is how it looks like

`[assembly: ExportRenderer(typeof(AlignedImage), typeof(AlignedImageRenderer))]
namespace MXExploreNew.Droid
{
public class AlignedImageRenderer : ImageRenderer
{
private Bitmap ViewImage;

    protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
    {
        base.OnElementChanged(e);

        if (e.OldElement == null)
        {
            if ((int)Android.OS.Build.VERSION.SdkInt < 18)
                SetLayerType(LayerType.Software, null);
        }

        e.NewElement.SizeChanged += NewElementOnSizeChanged;
    }

    protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);

    }

    private void NewElementOnSizeChanged(object sender, EventArgs eventArgs)
    {
        var alignedImage = sender as AlignedImage;
        if (alignedImage != null)
        {
            var winWidth = alignedImage.Width;
            var winHeight = alignedImage.Height;

            if ( this.Control.Drawable != null)
            {
               var sourceBitmap = Bitmap.CreateBitmap(this.Control.Drawable.IntrinsicWidth, this.Control.Drawable.IntrinsicHeight, Bitmap.Config.Argb8888);

                var imgHeight = sourceBitmap.Height;
                var imgWidth = sourceBitmap.Width;

                var cropFactor = Math.Min(imgHeight / winHeight, imgWidth / winWidth);
                var startFromX = imgWidth - winWidth * cropFactor;
                var startFromY = imgHeight - winHeight * cropFactor;

                var srcRect = new Rect(0, 0, imgWidth, imgHeight);

                Bitmap croppedImage = Bitmap.CreateBitmap((int)(winWidth * cropFactor), (int)(winHeight * cropFactor), Bitmap.Config.Rgb565);
                {
                    Canvas canvas = new Canvas(croppedImage);
                    Rect dstRect = new Rect((int)startFromX, (int)startFromY, (int)(winWidth * cropFactor), (int)(winHeight * cropFactor));
                    canvas.DrawBitmap(sourceBitmap, srcRect, dstRect, null);
                }

                using (var drawable = this.Control.Drawable) // don't remove, this is making sure memory isn't leaked
                {
                    this.Control.SetImageBitmap(croppedImage);
                }
            }
        }
    }`

Problem is that at his line
var sourceBitmap = Bitmap.CreateBitmap(this.Control.Drawable.IntrinsicWidth, this.Control.Drawable.IntrinsicHeight, Bitmap.Config.Argb8888);

I am always getting this.Control.Drawable.IntrinsicWidth with -1 value.
What am I doing wrong ?

Thanx,
D

Sign In or Register to comment.