根据内部画布调整customView大小



我有一个自定义视图,其中包含一个简单的画布(矩形)我想将此自定义视图的宽度和高度调整为画布的宽度和宽度因为当使用wrap_content时,自定义视图会填充的所有屏幕空间

非常感谢

布局:

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

自定义视图:

public class RectangleView   extends View {
    Paint paint = new Paint();
    public SquareLegendView(Context context) {
        super(context);
    }
    public SquareLegendView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public SquareLegendView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint.setColor(Color.BLACK);
        canvas.drawRect(40, 40, 80, 80, paint);
        //drawRect(left, top, right, bottom, paint)
    }
}

我知道这个问题已经在评论中得到了回答。但我只是想澄清一下。

问题陈述:

我想将此自定义视图的宽度和高度调整为画布宽度和高度


宽度&CustomView的高度与宽度&CCD_ 2画布的高度。

onDraw(Canvas canvas)方法中提供的canvas与视图本身具有相同的高度和宽度。因此,当您谈论View的大小时,您谈论的是canvas的大小。

现在,onMeasure()确定视图(或画布)的大小。无论您在此方法中通过setMeasuredDimension设置的大小都将是View的大小。

最新更新