0

I have a custom view which contains a simple canvas(rectangle) I want to adapt the width and height of this custom view to the canvas width and height Because when using wrap_content the custom view fills all the screen space

Thank you very much

Layout :

<?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>

Custom view:

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)
    }

}
ulquiorra
  • 931
  • 4
  • 19
  • 39
  • 1
    You need to override onMeasure method and setMeasuredDimension to desired width&height. Very good exlpanation here http://stackoverflow.com/questions/12266899/onmeasure-custom-view-explanation – aelimill Dec 30 '15 at 18:18
  • @aelimill Thanks it works great with onMeasure :). Create an answer so I can validate your solution ;) – ulquiorra Dec 31 '15 at 11:15

1 Answers1

0

I know this question has been answered in the comments. But I just wanted to add a bit of clarity.

The question states:

I want to adapt the width and height of this custom view to the canvas width and height


The width & height of the CustomView is the same as the width & height of the Canvas of onDraw.

The canvas supplied in the onDraw(Canvas canvas) method has the same height and width as that of the View itself. So when you talk about the size of the View, you are talking about the size of the canvas.

Now, onMeasure() determines the size of the View(or canvas). Whatever size you set here in this method via setMeasuredDimension will be size of the View.

Henry
  • 17,490
  • 7
  • 63
  • 98