Reputation: 11645
I know how to display a vector drawable using an ImageView by code (http://www.androidhive.info/2017/02/android-working-svg-vector-drawables/) , which is described in several articles, but:
How can I draw my vectors using my custom view and by code with canvas ? Is this possible to do. And if so, can someone give me a hint.
Upvotes: 11
Views: 7580
Reputation: 3344
I'm going to turn @pskink's comment into an answer as I'm not so advanced in android as to quickly realize what he meant. I had to read @Krishna's answer to understand. So credits to both of them. Here it goes:
A vector drawable inherits Drawable
that can be drawn directly into a canvas. First, get the drawable from the resources using an android context:
val drawable = yourContext.getDrawable(drawableId)
Then simply draw into the canvas with it. The next line tells the drawable to draw on the top left corner, with a size of 32x32 pixels:
drawable.setBounds(0, 0, 32, 32)
Finally draw it into the canvas:
drawable.draw(canvas)
Upvotes: 1
Reputation: 1634
To do this you need to convert the vector to a bitmap as follows:
private fun getVectorBitmap(context: Context, drawableId: Int): Bitmap? {
var bitmap: Bitmap? = null
when (val drawable = ContextCompat.getDrawable(context, drawableId)) {
is BitmapDrawable -> {
bitmap = drawable.bitmap
}
is VectorDrawable -> {
bitmap = Bitmap.createBitmap(
drawable.intrinsicWidth,
drawable.intrinsicHeight, Bitmap.Config.ARGB_8888
)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
}
}
return bitmap
}
Then you can use the vector as a bitmap normally with your canvas:
canvas?.drawBitmap(getVectorBitmap(context, R.drawable.ic_icon), 500f, 500f, canvasPaint)
Upvotes: 3