从 url 动态加载字体或从 lib 静态加载字体 [英] Loading typeface dynamically from url or statically from lib

查看:21
本文介绍了从 url 动态加载字体或从 lib 静态加载字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个 Android 应用程序,我想动态加载字体并在运行时使用它.我该怎么做?

I'm running an Android application and I want to load a font dynamically and use it during runtime. How can I do this?

还有如何在我编写的 SDK 中包含字体,在我编写的应用程序中引用 sdk,并使用 SDK 中包含的字体?

And also how can I include a font in an SDK that I've written, reference the sdk in the app I've written, and use the font included in the SDK?

感谢您对此投了 -1 票,无论是谁这样做,我都会停止分享知识,这是让我闭嘴的好方法.

Thanks for putting a -1 Vote on this, whoever did this, I'll stop sharing knowledge, that's a good way to shut me down.

推荐答案

我会这样做:(使用 AsyncTask,这并不完美)如果你想要比 AsyncTask 更稳定的东西,RxAndroid 提供了其他好的变体,更稳定.在此示例中,我在doInBackground"部分中执行所有操作,但您可以在任务完成后的任何地方以相同的方式使用它.此示例还假设我们具有从外部存储写入和读取的权限.

Here's how I would do it: (Using an AsyncTask, which is not perfect) If you want something more stable than an AsyncTask RxAndroid offers other good variants, far more stable. In this example I'm doing everything in the "doInBackground" section, but you can use it the same way, anywhere after the task is done. This example also assumes we have persmissions to write and read from external storage.

    private class DownloadTask extends AsyncTask<String, Integer, String> {

    private Context context;

    public DownloadTask(Context context) {
        this.context = context;
    }

    @Override
    protected String doInBackground(String... sUrl) {
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(sUrl[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            // expect HTTP 200 OK, so we don't mistakenly save error report
            // instead of the file
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return "Server returned HTTP " + connection.getResponseCode()
                        + " " + connection.getResponseMessage();
            }

            // download the file
            input = connection.getInputStream();
            File sdCard = Environment.getExternalStorageDirectory();
            File dir = new File (sdCard.getAbsolutePath() + "/fonts");
            dir.mkdirs();
            File file = new File(dir, "font.ttf");
            try {
                OutputStream out = new FileOutputStream(file);
                byte[] buf = new byte[1024];
                int len;
                while((len=input.read(buf))>0){
                    out.write(buf,0,len);
                }
                out.close();
                input.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            File sdcard = Environment.getExternalStorageDirectory();
            File dirs = new File(sdcard.getAbsolutePath()+"/fonts");

            if(dirs.exists()) {
                File[] files = dirs.listFiles();
                Log.d("s","files");
            }
            final Typeface typeface = Typeface.createFromFile(
                    new File(Environment.getExternalStorageDirectory()+"/fonts", "font.ttf"));
            Log.d("a","created");
            // Now I'm starting with an example that shows how to use 
            // this font on a textview of my choice.
            // Assumptions: font has characters uF102 and uF104
            final TextView tv = (TextView) findViewById(R.id.myTextView);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (tv != null && typeface != null) {
                        tv.setTypeface(typeface);
                        tv.setText("uF102");
                        tv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (tv.getText().equals("uF102")){
                                    tv.setText("uF104");
                                } else {
                                    tv.setText("uF102");
                                }
                            }
                        });
                    }
                }
            });

        } catch (Exception e) {
            return e.toString();
        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
            }

            if (connection != null)
                connection.disconnect();
        }
        return null;
    }
}

如果我们想从我们正在使用的 sdk 或我们编写的库中加载字体,我们可以将字体包含在可绘制的原始部分中,并且从使用这个 sdk/lib 的应用程序中我们可以像这样引用字体:(我在这个例子中使用了 amaticobold 字体)

In case we want to load the font from an sdk we're using, of from a library we've written, we can include the font in the drawable raw section, and from the application using this sdk/lib we can reference the font like so: (I've used the amaticobold font in this case just for example)

        File sdCard = Environment.getExternalStorageDirectory();
    File dir = new File (sdCard.getAbsolutePath() + "/fonts");
    dir.mkdirs();
    File file = new File(dir, "font.ttf");
    InputStream is = getResources().openRawResource(getResources().getIdentifier("amaticbold","raw", getPackageName()));
    try {
        OutputStream out = new FileOutputStream(file);
        byte[] buf = new byte[1024];
        int len;
        while((len=is.read(buf))>0){
            out.write(buf,0,len);
        }
        out.close();
        is.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    File sdcard = Environment.getExternalStorageDirectory();
    File dirs = new File(sdcard.getAbsolutePath()+"/fonts");

    if(dirs.exists()) {
        File[] files = dirs.listFiles();
        Log.d("s","files");
    }
    final Typeface typeface = Typeface.createFromFile(
            new File(Environment.getExternalStorageDirectory()+"/fonts", "font.ttf"));
    editText.setTypeface(typeface);

这篇关于从 url 动态加载字体或从 lib 静态加载字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆