【问题标题】:adapt customView size to inner canvas使 customView 大小适应内部画布
【发布时间】: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


【解决方案1】:

我知道这个问题已经在 cmets 中得到了解答。但我只是想增加一点清晰度。

问题说明:

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


CustomView的宽高与onDraw的Canvas的宽高一致。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-29
    • 2015-07-06
    • 2015-08-31
    • 2010-12-12
    • 1970-01-01
    • 2014-05-07
    • 2021-06-22
    • 2015-09-15
    相关资源
    最近更新 更多