VectorDrawable: How to position it on canvas?

Ersen Osman picture Ersen Osman · Jun 3, 2016 · Viewed 13.5k times · Source

For my custom view:

MyCustomView extends View 

I made a VectorDrawable

mMyVectorDrawable = VectorDrawableCompat.create(getContext().getResources(), R.drawable.ic_some_image, null);

I have set its bounds

mMyVectorDrawable.setBounds(0, 0, mMyVectorDrawable.getIntrinsicWidth(), mMyVectorDrawable.getIntrinsicHeight());

And I draw it on the Canvas

mMyVectorDrawable.draw(canvas);

I see the image at position 0,0

but how do I position it? How do I position the Rect, I thought the first two params of setBounds would be X and Y coordinates of where to start drawing but this just affects the size.

How can I position my vector drawable on a canvas?

Answer

Danilo Bargen picture Danilo Bargen · Oct 21, 2016

You can translate your canvas before drawing the drawable onto it.

mMyVectorDrawable.setBounds(0, 0, width, height);
canvas.translate(dx, dy);
mMyVectorDrawable.draw(canvas);

The values dx and dy specify the offset from the coordinates (0, 0) where the next drawable will be drawn.

If you want, you can also undo the translation afterwards:

canvas.translate(-dx, -dy);