Search code examples
javaandroidhuawei-mobile-serviceshuawei-developersharmonyos

How to set a custom font style to a text in Harmony Os i.e setting a new font which is not pre defined in Harmony OS?


I wanted to change the font style of text component(dayTitle) to a custom font for my project. For setting a predefined font ex:- BOLD, Harmony OS platform allows the users to set the predefined fonts in this manner -

dateTitle.setFont(Font.DEFAULT_BOLD)

Is there any way that I can set custom font to my text component(dayTitle)?


Solution

  • Place your custom font inside resources/rawfile/ and use the following snippet to access the custom font from resources directory,

        Font createFontBuild(Context context, String name) {
            ResourceManager resManager = context.getResourceManager();
            RawFileEntry rawFileEntry = resManager.getRawFileEntry("resources/rawfile/" + name);
            Resource resource = null;
            try {
                resource = rawFileEntry.openRawFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            StringBuffer fileName = new StringBuffer(name);
            File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), fileName.toString());
            OutputStream outputStream = null;
            try {
                outputStream = new FileOutputStream(file);
                int index;
                byte[] bytes = new byte[1024];
                while ((index = resource.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, index);
                    outputStream.flush();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    resource.close();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
            }
            Font.Builder builder = new Font.Builder(file);
            return builder.build();
        }