Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Draw a view on canvas

I have a view inflated, I can draw it on canvas, but can't seem to position it properly.

LayoutInflater li = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.fix_this_recommendation, null);
v.measure(MeasureSpec.getSize(v.getMeasuredWidth()), MeasureSpec.getSize(v.getMeasuredHeight()));
v.layout(400, 400, 400, 400);
v.draw(canvas);

But the view is always at the top left corner. Anyone know why?

like image 252
Johnny Avatar asked Feb 09 '12 02:02

Johnny


2 Answers

Solution is to translate canvas:

canvas.save();
canvas.translate(left, top);            
view.draw(canvas);
canvas.restore();
like image 131
Peterdk Avatar answered Sep 27 '22 22:09

Peterdk


Each View draws its contents within its own coordinate system, with (0, 0) at the top-left. If you want it to appear elsewhere, you can set a new transformation matrix on your Canvas.

like image 22
Lawrence D'Oliveiro Avatar answered Sep 27 '22 23:09

Lawrence D'Oliveiro