调整自定义视图的报告大小以包括绘制的图形

时间:2014-01-16 00:50:58

标签: android canvas view measure

我有一个自定义视图类(称为FooView),我将其用作xml布局的根元素。 FooView在其onDraw()中使用canvasFooView的底部边缘绘制形状。

我认为,为了让FooView不切断形状,我需要覆盖其onMeasure并做一些修改FooView报告高度的内容,以便它现在包含绘制形状的那个。

这是对的吗?如果是这样,我需要做什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

是的,如果您要创建自定义视图,则需要覆盖onMeasure()并提供所需的大小。

因此,在onMeasure的方法签名中,您将获得两个参数:

  • widthMeasureSpec
  • heightMeasureSpec

您应该使用MeasureSpec类来获取在调整视图大小时应该遵守的限制。

/*
 * This will be one of MeasureSpec.EXACTLY, MeasureSpec.AT_MOST, 
 * or MeasureSpec.UNSPECIFIED
 */
int mode = MeasureSpec.getMode(measureSpec);

//This will be a dimension in pixels
int pixelSize = MeasureSpec.getSize(measureSpec);

如果你得到MeasureSpec.EXACTLY,那么你应该使用pixelSize值作为测量宽度,无论如何。

如果您获得MeasureSpec.AT_MOST,则应确保将测量的宽度设置为不大于pixelSize

如果您获得MeasureSpec.UNSPECIFIED,则可以根据需要腾出更多空间。我通常只将其解释为WRAP_CONTENT

因此,您的onMeasure()方法可能如下所示:

@Override
protected void onMeasure (int widthSpec, int heightSpec) {
    int wMode = MeasureSpec.getMode(widthSpec);
    int hMode = MeasureSpec.getMode(heightSpec);
    int wSize = MeasureSpec.getSize(widthSpec);
    int hSize = MeasureSpec.getSize(heightSpec);

    int measuredWidth = 0;
    int measuredHeight = 0;

    if (wMode == MeasureSpec.EXACTLY) {
        measuredWidth = wSize;
    } else {
        //Calculate how many pixels width you need to draw your View properly
        measuredWidth = calculateDesiredWidth();

        if (wMode == MeasureSpec.AT_MOST) {
            measuredWidth = Math.min(measuredWidth, wSize);
        }
    }

    if (hMode == MeasureSpec.EXACTLY) {
        measuredHeight = hSize;
    } else {
        //Calculate how many pixels height you need to draw your View properly
        measuredHeight = calculateDesiredHeight();

        if (hMode == MeasureSpec.AT_MOST) {
            measuredHeight = Math.min(measuredHeight, hSize);
        }
    }

    setMeasuredDimension(measuredWidth, measuredHeight);
}