为android webview添加自定义字体



我想开发一个简单的android网络浏览器应用程序,支持我提供的Unicode字体。我做了一些研究,但我找不到一个成功的方法来为android WebView添加自定义字体。有一些解决方案可以为WebView添加自定义字体,但它们都是基于在CSS中添加字体。但由于我无法控制我在WebView中加载的页面,是否有一种方法可以像TextViewsetTypaFace()方法一样直接向WebView添加字体。?

以下是我迄今为止为webview添加自定义字体的代码:

package com.example.sinhalafontrendering;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Menu;
import android.webkit.WebView;
import android.widget.TextView;
import com.example.sinhalafontrendering.R.id;
public class MainActivity extends Activity {
    WebView mWebView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FontUtils.setCustomFont(findViewById(id.txtHelloWorld), getAssets());
        Typeface tf = Typeface.createFromAsset(getAssets(), "iskpota.ttf");
        TextView tv = (TextView) findViewById(id.txtHelloWorld);
        tv.setText("ශ්‍රී ලංකා, n ");
        //tv.setTypeface(tf,0);
        String html = "<html><head><style type="text/css">@font-face { font-family: MyCustomFont; src: url("Bamini.eot") /* EOT file for IE */}@font-face { font-family: MyCustomFont; src: url("file:///android_asset/iskpota.ttf") /* TTF file for CSS3 browsers */}body { font-family: MyCustomFont, Verdana, Arial, sans-serif;font-size: medium;color: black}</style></head><body><LI><a href="http://www.thelastrow.lk/">ශ්‍රී ලංකා;</a></LI></UL></div></body></html>";
        mWebView = (WebView) findViewById(R.id.webGoogle);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setSupportZoom(true);
        //mWebView.loadUrl("file:///android_asset/a.html");
        mWebView.loadDataWithBaseURL("www.thelastrow.lk", html, "text/html", "UTF-8", null);
        mWebView.setWebViewClient(new HelloWebViewClient());

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

它与loadDataWithBaseURL一起工作!

对于这个例子,我将CSS更改为:

@font-face {
    font-family: 'feast';
    src: url('fonts/feasfbrg.ttf');
}
body {font-family: 'feast';}

然后使用资产路径作为基本url:

loadDataWithBaseURL("www.google.com",myhtml,"text/html","utf-8",null);

最新更新