1

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.

0

1 Answer 1

1

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);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.