OnDraw:Canvas不绘制位图

时间:2015-09-26 16:36:34

标签: c# android xamarin android-canvas android-custom-view

我正在使用Xamarin.Android制作自定义视图,我想在画布上绘制一个圆圈,然后在其上绘制一个位图。圆圈正在绘制,但位图不是 位图对应于png图像资源。 这是我的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);

    }

编辑:Resources.TryGetColor是一个扩展方法,我创建了。

1 个答案:

答案 0 :(得分:1)

我注意到旋转屏幕时会显示位图的一部分。 问题出在位图边界上,所以我按如下方式解决了这个问题:

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