0

我创建了我的自定义可绘制对象。为了绘制它,我使用了边界。但是,当用户使用:

android:layout_width="match_parent"
android:layout_height="wrap_content"

我得到 bounds.height() == 1。然后,我想用作 height = 0.8 * bounds.width。

我试过了,因为当用户使用 WRAP_CONTENT 时,我得到 bounds.height() = 1。所以我将可绘制高度设置为 0.8*width()。但我没有得到合适的尺寸。我只是觉得高度是 1。我读到你需要调用 invalidate(),但是我该如何调用它,因为如果我在draw()中调用 invalidate(),那么该方法将被无限调用。

4

2 回答 2

2

您应该使用 onMeasure 方法。

当需要使您正在处理的视图大小无效时,生命周期调用它。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    ViewGroup.LayoutParams params = getLayoutParams();

    //height and width expected from wrap_content and match_parent
    int newHeight = MeasureSpec.getSize(heightMeasureSpec);
    int newWidth = MeasureSpec.getSize(widthMeasureSpec);
    int myHeight= newWidth * 0.8;

height = myHeight
    width = newWidth
}
于 2019-11-13T10:40:41.027 回答
1

考虑使用layout_constraintDimensionRatioConstraintLayout官方 指南

或者你也可以在onMeasure().

于 2019-11-13T10:41:14.650 回答