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

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

问题描述

我正在运行一个Android应用程序,我想动态加载一个字体并在运行时使用它。我怎样才能做到这一点?



另外,如何在我写的SDK中包含字体,在我写的应用程序中引用sdk,使用包含在SDK中的字体?

编辑:感谢您对此投入了-1票,谁做了这个,我会停止分享知识,这是一个好方法关闭我。

解决方案

下面是我要做的事情:(使用AsyncTask,这不是完美的)
如果你想要比AsyncTask更稳定的东西RxAndroid提供了其他更好的变体,更稳定。
在这个示例中,我正在做doInBackground部分中的所有内容,但是可以在任务完成后的任何位置以相同的方式使用它。
这个例子还假定我们有从外部存储器读写的保留。

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

private上下文;

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

@Override
保护字符串doInBackground(String ... sUrl){
InputStream input = null;
OutputStream output = null;
HttpURLConnection连接= null;
尝试{
URL url = new URL(sUrl [0]);
connection =(HttpURLConnection)url.openConnection();
connection.connect();

// expect HTTP 200 OK,所以我们不会错误地保存错误报告
//而不是文件
if(connection.getResponseCode()!= HttpURLConnection.HTTP_OK ){
returnServer returned HTTP+ connection.getResponseCode()
++ connection.getResponseMessage();
}

//下载文件
input = connection.getInputStream();
文件sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath()+/ fonts);
dir.mkdirs();
档案档案=新档案(dir,font.ttf);
尝试{
OutputStream out = new FileOutputStream(file);
byte [] buf = new byte [1024];
int len; ((len = input.read(buf))> 0){
out.write(buf,0,len);
}
out.close();
input.close();
} catch(Exception e){
e.printStackTrace();
}
文件sdcard = Environment.getExternalStorageDirectory();
文件dirs =新文件(sdcard.getAbsolutePath()+/ fonts);

if(dirs.exists()){
File [] files = dirs.listFiles();
Log.d(s,files);

最终字体typeface = Typeface.createFromFile(
new File(Environment.getExternalStorageDirectory()+/ fonts,font.ttf));
Log.d(a,created);
//现在我开始一个例子,演示如何在我选择的textview上使用
//这个字体。
//假设:字体有字符uF102和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(\\\);
tv.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
if(tv.getText()。equals(\\\)){
tv.setText(\\\);
} else {
tv.setText(\\\);
}
}
});
}
}
});
$ b $ catch(Exception e){
return e.toString();
} finally {
try {
if(output!= null)
output.close();
if(input!= null)
input.close();
} catch(IOException忽略){
}

if(connection!= null)
connection.disconnect();
}
返回null;




$ b $ p
$ b $ p如果我们想从sdk载入字体我们使用的是从我们编写的库中,我们可以在可绘制的原始部分中包含字体,使用这个sdk / lib的应用程序可以像这样引用字体:
(I've在这种情况下使用amaticobold字体就是这样)

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

if(dirs.exists()){
File [] files = dirs.listFiles();
Log.d(s,files);

最终字体typeface = Typeface.createFromFile(
new File(Environment.getExternalStorageDirectory()+/ fonts,font.ttf));
editText.setTypeface(typeface);


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

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?

Edit: 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.

解决方案

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;
    }
}

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天全站免登陆