Visual的DispatchDraw方法不起作用

时间:2017-05-11 02:36:10

标签: java c# android xamarin xamarin.android

我试图覆盖View类的DispatchDraw方法来显示某些东西。我的View类如下:

public class MyCustomButton : View
{
    private Paint colorPaint;
    public MyCustomButton(Context context, IAttributeSet attrs) : base(context, attrs)
    {
        colorPaint = new Paint();
        colorPaint.Color = Color.Argb(0, 255, 0, 0);
    }
    protected override void DispatchDraw(Canvas canvas)
    {
        canvas.DrawText("aaa", 0, 0, colorPaint);
    }
}

活动布局文件(Xamarin中的axml文件)如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <Hw005_UiControls.MyCustomButton
        android:id="@+id/myBtn"
        android:layout_width="match_parent"
        android:layout_height="64dp"
        android:background="@android:color/holo_blue_bright" />
</RelativeLayout>

我的MainActivity类的OnCreate方法如下:

...
SetContentView(Resource.Layout.ButtonView5);
View view = FindViewById(Resource.Id.myBtn) as View;
view.Invalidate();
...

我跟踪那些代码,每行代码都可以执行,但字符串“aaa”可以 显示。我使用xamarin但是在这种情况下它几乎和java一样。所以是 有人可以给我一些解决这个问题的技巧吗?

非常感谢

1 个答案:

答案 0 :(得分:0)

如果您使用DispatchDraw并且需要呈现ViewGroup个孩子,则通常会使用

View。此外,Y DrawText参数是文本的基线,而不是Y 来源

使用OnDraw覆盖的示例:

protected override void OnDraw(Android.Graphics.Canvas canvas)
{
    base.OnDraw(canvas); // call base here you want to draw the subclassed View content under your custom drawing
    using (var colorPaint = new Paint())
    {
        colorPaint.Color = Color.Rgb(255, 0, 0);
        colorPaint.TextSize = 30;
        canvas.DrawText("StackOverflow", 10, 30, colorPaint);
    }
    //base.OnDraw(canvas); // call base here you want to draw the subclassed View content over your custom drawing
}

在Button子类上的OnDraw覆盖:

protected override void OnDraw(Android.Graphics.Canvas canvas)
{
    base.OnDraw(canvas);
    using (var colorPaint = new Paint())
    {
        colorPaint.Color = Color.Rgb(255, 0, 0);
        colorPaint.TextSize = 30;
        canvas.DrawText("StackOverflow", 12, 32, colorPaint);
        colorPaint.Color = Color.Rgb(255, 255, 255);
        canvas.DrawText("StackOverflow", 10, 30, colorPaint);
    }
}

enter image description here