NikW
NikW

Reputation: 347

Android - How to set width and height for customview in OnDraw() with Canvas?

I am trying to set the Width and Height for a customview on which I use Canvas to draw.

Have noticed that onDraw() always sets to a default width and height, and not take the values as specified in layout xml or set using the onMeasure method.

Could some one help me where I am going wrong.

Thanks

@Override
protected void onMeasure(final int widthMeasureSpec,
                         final int heightMeasureSpec) {
     super.onMeasure(widthMeasureSpec, heightMeasureSpec);
     setMeasuredDimension(getMeasuredWidth(), getMeasuredHeight());
}

Upvotes: 0

Views: 843

Answers (1)

Fahime Zivdar
Fahime Zivdar

Reputation: 431

you can use this code

public class CustomView extends View{
private Paint paint;
private int w;
private int h;

public CustomView(Context context, AttributeSet attr) {
    super(context, attr);
    paint = new Paint();
    paint.setTextAlign(Align.CENTER);
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    this.w = w;
    this.h = h;
    super.onSizeChanged(w, h, oldw, oldh);
}

@Override
protected void onDraw(Canvas canvas) {
    canvas.drawColor(Color.WHITE);
    canvas.drawText("TEST", w/2, h/2, paint);   
}

}

Upvotes: 2

Related Questions