绘制自定义视图的正确方法?

Proper way to draw custom view?

我正在尝试实现由某些数据创建的自定义视图 - 具体来说,我正在尝试通过自定义视图创建收入预测图。

我这样做的方法是有 10 个数据点,并在每个数据点之间画线。 (然后还绘制了 X 和 Y 轴线)。

我正在考虑创建一个封装 10 个坐标的视图,并通过 onDraw() 中的 canvas 绘制它们。像这样:

class RevView extends View {
    private List<Point> mPoints;
    public void configurePoints(float[] revenues) { 
        // convert revenues to points on the graph.
    }
    // ... constructor... etc.
    protected void onDraw(Canvas canvas) {
        // use canvas.drawLine to draw line between the points
    }
}

但为了这样做,我想我需要 width/height 视图,它直到 onDraw.

才呈现

这是正确的方法吗?或者我什至应该将 Points 列表传递给视图?或者有什么更好的构建方法?

您应该覆盖将在 onDraw() 之前调用的 onMeasure() 方法。

https://developer.android.com/reference/android/view/View.html#onMeasure(int,%20int)

Measure the view and its content to determine the measured width and the measured height.

您应该使用在 onDraw() 方法之前调用的 onMeasure() 方法,这样您就可以得到您的像这样查看维度:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int width = measureWidth(widthMeasureSpec);
    int height = measureHeight(heightMeasureSpec);
}

您应该避免直接在 onDraw() 方法中获取视图尺寸,因为它会在一秒钟内被调用多次