Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Vector Drawable by drawing in Canvas

  • I have a imported an SVG into my project as Vector Drawable.
  • I have my custom view

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.

like image 233
mcfly soft Avatar asked Jun 18 '17 06:06

mcfly soft


1 Answers

 In onDraw method

  canvas?.drawBitmap(getVectorBitmap(context, R.drawable.ic_icon), 500f, 500f, canvasPaint)


 create below method in class

  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
}
like image 107
Krishna Avatar answered Oct 24 '22 20:10

Krishna