关于自定义view的onDraw方法中画的图形坐标问题

发生的问题:自定义View使用onDraw方法画出一个矩形填充整个View,然后把控件作为布局的头一个子view显示是没问题,但是如果不是第一个子view,比如在它上面或者左边放一个TextView,自定义的控件是位置是没错,但是控件里面画的图形就会发生移动,有一部分移出自定义view。
自定义view代码 :

public class CircularView extends View {

    private Rect mRect;
    private Paint mPaint;

    public CircularView(Context context) {
        super(context);
    }

    public CircularView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint();
        mRect = new Rect();
    }
		
    @Override
    protected void onDraw(Canvas canvas) {
        Log.i(MainActivity.TAG, "onDraw: " + getTop());
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.GREEN);
        //矩形填充控件
        mRect.left = getLeft();
        mRect.top = getTop();
        mRect.bottom = getBottom();
        mRect.right = getLeft() + getWidth();
        canvas.drawRect(mRect, mPaint);
    }
}

自定义View作为布局第一个控件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"

    android:layout_height="match_parent">
  

<com.example.hp_pc.testapplication.view.custom.CircularView
    android:layout_width="match_parent"
    android:layout_height="50dp"/>


</LinearLayout>

显示是这样的:
关于自定义view的onDraw方法中画的图形坐标问题
这是预料之中的

自定义view在布局中不是第一个view:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv"
        android:text="@string/appbar_scrolling_view_behavior"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

<com.example.hp_pc.testapplication.view.custom.CircularView
    android:layout_width="match_parent"
    android:layout_height="50dp"/>


</LinearLayout>

画的矩形位移了,从布局预览来看View本身没有出错,但是画的图形出错了:
关于自定义view的onDraw方法中画的图形坐标问题
意料之外!

问题解决:
其实出现问题是在绘制图形时定位图形坐标,也就是这里:

mRect.left = getLeft();  
mRect.top = getTop();
mRect.bottom = getBottom();
mRect.right = getLeft() + getWidth();

这里画的矩形坐标都是相对布局的,而在view中画图应该根据view内部来定坐标的,也就是改成这样:

//填充整个控件
mRect.left = 0;
mRect.top = 0;
mRect.bottom = getHeight();
mRect.right = getWidth();

OK,解决
关于自定义view的onDraw方法中画的图形坐标问题