Jalal Mostafa
Jalal Mostafa

Reputation: 1024

OnDraw : Canvas is not drawing bitmap

I am making a custom view using Xamarin.Android, I want draw a circle then a bitmap over it in the canvas. The circle is being drawn properly but the bitmap isn't The bitmap corresponds to a png image resource. Here is my OnDraw

    protected async override void OnDraw(Canvas canvas)
    {
        base.OnDraw(canvas);
        Paint buttonBackgroundPaint = new Paint(PaintFlags.AntiAlias);
        Color? c = null;
        bool colorOk = Resources.TryGetColor(_backgroundColor, out c);

        buttonBackgroundPaint.Color = (Color)(colorOk ? c : _context?.Resources.GetColor(AndroidRes.Resource.Color.Black));
        canvas.DrawCircle(Width / 2, Height / 2, _radius, buttonBackgroundPaint);

        Paint bitmapPaint = new Paint(PaintFlags.AntiAlias);
        Bitmap bitmapContent = await BitmapFactory.DecodeResourceAsync(_context?.Resources, _drawableContent);
        canvas.DrawBitmap(bitmapContent, 0, 0, bitmapPaint);

    }

EDIT : Resources.TryGetColor is an extension method, I've created.

Upvotes: 1

Views: 823

Answers (1)

Jalal Mostafa
Jalal Mostafa

Reputation: 1024

I've noticed that a part of the bitmap is showing when rotating screen. the problem was with the bitmap bounds, so I solved it as follows:

protected async override void OnDraw(Canvas canvas)
{
    base.OnDraw(canvas);
    Paint buttonBackgroundPaint = new Paint(PaintFlags.AntiAlias);
    Color? c = null;
    bool colorOk = Resources.TryGetColor(_backgroundColor, out c);

    buttonBackgroundPaint.Color = (Color)(colorOk ? c : _context?.Resources.GetColor(AndroidRes.Resource.Color.Black));
    canvas.DrawCircle(Width / 2, Height / 2, _radius, buttonBackgroundPaint);

    Drawable dr = _context.Resources.GetDrawable(Resource.Drawable.image);
    dr.SetBounds(0, 0, right, bottom); // appropiate values for my case
    dr.Draw(canvas);
}

Upvotes: 1

Related Questions