牛骨文教育服务平台(让学习变的简单)
博文笔记

Android webview 使用自定义字体

创建时间:2015-09-10 投稿人: 浏览次数:1872

原文:http://blog.isming.me/2015/07/07/android-custom-font/

最近的一个项目中有个需求:app与webview需要统一使用自定义字体。

一:修改App的默认字体

1.把myfont.ttf放在assets/fonts 目录下

2.配置Calligraphy

dependencies {    compile "uk.co.chrisjenx:calligraphy:1.2.0"}  githut地址:https://github.com/chrisjenx/Calligraphy

2.在 BaseApplication extends Application 的onCreate 方法中

 CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
                        .setDefaultFontPath("fonts/myfont.ttf")
                        .setFontAttrId(R.attr.fontPath)
                        .build()
3.在BaseActivity 中重写attachBaseContext方法
 protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }
二:修改webview里网页的字体:

1.对于本地的网页,在asset目录放字体文件,并在css中添加以下内容,自定义一个字体face,并且在需要的地方使用这个字体face即可。

@font-face {
	  font-family: "MyCustomFont";
	  src: url("file:///android_asset/fonts/myfont.ttf"); 
	}
	body{
	  font-family:"MyCustomFont";
	}

2.对于在线的网页,则需要把字体文件放到服务器,使用同样的方式定义字体face,应用到每个地方。

为了减少网页或者说服务器端的工作,可以使用本地注入的方式注入font-face的css,并对整个网页进行样式替换。

给webview自定义webViewClient,重写onPageFinish,在其中添加如下内容:

public void onPageFinished(WebView view, String url) {
				injectCSS();
				view.loadUrl("javascript:!function(){" +
				        "s=document.createElement("style");s.innerHTML="
				        + ""@font-face{font-family:myhyqh;src:url("****/fonts/myfont.ttf");}*{font-family:myhyqh !important;}";"
				        + "document.getElementsByTagName("head")[0].appendChild(s);" +
				        "document.getElementsByTagName("body")[0].style.fontFamily = "myhyqh";}()");
				super.onPageFinished(view, url);
			}

****/fonts/myfont.ttf  //这里的* 号是为了让它走:shouldInterceptRequest
重写vwebview的shouldInterceptRequest方法:

public WebResourceResponse shouldInterceptRequest(WebView view,
					String url) {
				WebResourceResponse response = super.shouldInterceptRequest(view, url);
				Log.i("webview","load intercept request:" + url);
				 if (url != null && url.contains("myfont.ttf")) {
				        String assertPath ="fonts/myfont.ttf";
				        try {
				            response = new WebResourceResponse("application/x-font-ttf","UTF8", getAssets().open(assertPath));
				        } catch (IOException e) {
				            e.printStackTrace();
				        }
				    }
				return response;
			}

这样网页被新字体重新渲染就达到目的了



声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。