Font in Android Library

后端 未结 9 1615
南方客
南方客 2021-02-05 15:30

At the follow link

Android Dev Guide

is write:

Library projects cannot include raw assets The tools do not support the use of raw asset files (saved in t

9条回答
  •  生来不讨喜
    2021-02-05 16:13

    Here's my modified version/improvement on @Mr32Bit's answer. On the first call, I copy the font to the app private dir /custom_fonts. Future reads check if exists and if so reads existing copy (saves time on coping file each time).

    note: This assumes only a single custom font.

     /**
         * Helper method to load (and cache font in app private folder) typeface from raw dir this is needed because /assets from library projects are not merged in Eclipse
         * @param c
         * @param resource ID of the font.ttf in /raw
         * @return
         */
        public static Typeface loadTypefaceFromRaw(Context c, int resource)
        {
            Typeface tf = null;
    
            InputStream is = c.getResources().openRawResource(resource);
            String path = c.getFilesDir() + "/custom_fonts";
            File f = new File(path);
            if (!f.exists())
            {
                if (!f.mkdirs())
                    return null;
            }
    
            String outPath = path + "/myfont.ttf";
    
            File fontFile = new File(outPath);
            if (fontFile.exists()) {
                tf = Typeface.createFromFile(fontFile);
            }else{
                try
                {
                    byte[] buffer = new byte[is.available()];
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outPath));
                    int l = 0;
                    while((l = is.read(buffer)) > 0)
                    {
                        bos.write(buffer, 0, l);
                    }
                    bos.close();
                    tf = Typeface.createFromFile(outPath);
                }
                catch (IOException e)
                {
                    return null;
                }
            }
            return tf;
        }
    

提交回复
热议问题