【发布时间】:2015-12-30 17:48:28
【问题描述】:
我有一个自定义视图,其中包含一个简单的画布(矩形)
我想将此自定义视图的宽度和高度调整为画布宽度和高度
因为在使用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)
}
}
【问题讨论】:
-
您需要重写 onMeasure 方法并将MeasuredDimension 设置为所需的宽度和高度。很好的解释stackoverflow.com/questions/12266899/…
-
@aelimill 感谢它与 onMeasure 配合得很好 :)。创建一个答案,以便我验证您的解决方案;)
标签: android android-canvas android-custom-view