Android: Draw a view on canvas
17,523
Solution 1
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.
Solution 2
Solution is to translate canvas:
canvas.save();
canvas.translate(left, top);
view.draw(canvas);
canvas.restore();
Solution 3
because the coordinate system used in the Canvas
starts from the top left corner instead of doing that define your Custom View and override the onDraw()
method and inside it position your view as you like
Related videos on Youtube
Author by
Johnny
Updated on July 06, 2022Comments
-
Johnny almost 2 years
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?
-
Johnny over 12 yearsThis is what I am doing, the code above is inside the onDraw() function. Am I missing something?
-
Johnny over 12 yearsThat make sense now, the issue was the subviews are not drawing properly. So what does "layout" do then?
-
Peterdk over 10 yearsIs there any info on how to exactly do this? I am facing the same problem.