androidandroid-canvasandroid-custom-view

Is there a way to store a vector graphic in the app's package and load it on runtime into a canvas?


I want to build an app where you can draw ancient hieroglyphs on a canvas in a custom view.

I have to provide over 1000 hieroglyphs in vector graphic format (for scaling mirroring etc.). The provided vector graphics must be anywhere in the apk package (so I don't have to download them after the installation) and they have to be accessable by the app. The Idea is that I am typing A12 in a textfield and the app is looking for the graphic with the id A12 in the folder (or were the graphics are stored).

So I wonder if there is a way to store the vector graphics in a folder of the apk package and access them later in the app and draw them on a canvas.

I've seen another question on Stack Overflow which was dealing a similar problem but I could not find it.

What is the most efficient way to do this?


Solution

  • In my opinion the right approach, since it's a lot of files, would be to download them after installation.

    However since you don't want to, you can convert them to Android VectorDrawables Which work like SVGs file in android and can be used as drawable resource.

    A VectorDrawable is a vector graphic defined in an XML file as a set of points, lines, and curves along with its associated color information.

    The conversion can be done in AndroidStudio itself check this question if you're intersted (Basically you can right-click to create a VectorDrawable and select a .svg file to import)

    Then you can place the .xml files inside the drawable folder and fetch the drawable in Android studio with the resource R.drawable.your_file

    A basic implementation would be like

    int gliph_id = 0;
    
    //You can use whatever way to store the ids, depends on your case, maybe an HashMap<String,Integer>?
    glyph_id = hieroglyphMap.get(glyph_name);
    
    Drawable hieroglyph = ContextCompat.getDrawable(context, glyph_id);
    hieroglyph.setBounds(0, 0, 100, 100);
    hieroglyph.draw(canvas);
    

    If you have any suggestion to improve the answer you re welcome to help

    Hope this helps you