Font in Android Library

后端 未结 9 1617
南方客
南方客 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 15:48

    Here's a method for loading fonts from resources that actually works ;-) Credit to mr32bit for the first version.

    private Typeface getFontFromRes(int resource)
    { 
        Typeface tf = null;
        InputStream is = null;
        try {
            is = getResources().openRawResource(resource);
        }
        catch(NotFoundException e) {
            Log.e(TAG, "Could not find font in resources!");
        }
    
        String outPath = getCacheDir() + "/tmp" + System.currentTimeMillis() ".raw";
    
        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);
    
            // clean up
            new File(outPath).delete();
        }
        catch (IOException e)
        {
            Log.e(TAG, "Error reading in font!");
            return null;
        }
    
        Log.d(TAG, "Successfully loaded font.");
    
        return tf;      
    }
    

提交回复
热议问题