【筆記】WebView如何引用本地字型
步驟1:準備字型,字尾為ttf,otf格式。可以去綠鬥堂字型網下載http://www.lvdoutang.com
步驟2:把字型拷貝到專案工程mian\assets\fonts目錄下。
步驟3:在assets目錄下建立.css檔案。
參考格式:
/** 微軟雅黑 */
@font-face {
font-family: 'Microsoft YaHei';
src: url('file:///android_asset/fonts/Microsoft_YaHei.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
/** 黑體 */
@font-face {
font-family: 'SimHei';
src: url('file:///android_asset/fonts/SimHei.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
/** 宋體 */
@font-face {
font-family: 'SimSun';
src: url('file:///android_asset/fonts/SimSun.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
/** 宋體(預設) */
@font-face {
font-family: 'FangSong_GB2312';
src: url('file:///android_asset/fonts/FangSong_GB2312.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
步驟4:拼接後臺返回的富文字格式的Json
參考方法:
public static String getNewContent(String htmltext, String title) {
Document doc = Jsoup.parse(htmltext);
Elements elements1 = doc.getElementsByTag("img");
Elements elements2 = doc.getElementsByTag("a");
for (Element element : elements1) {
element.attr("width", "100%").attr("height", "auto");
}
for (Element element : elements2) {
element.attr("style", "word-wrap:break-word");
}
String assetsFontCSS = "<link href=\"file:///android_asset/myfont.css\" rel=\"stylesheet\" type=\"text/css\"/>\n";
String htmlSource = doc.toString();
String htmlAdded = htmlSource.replace("</head>",
"\n" + assetsFontCSS +
"<meta charset=\"UTF-8\"/>\n" +
"<meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no\"/>\n" +
"<title>" + title + "</title>\n" +
"</head>").replace("<body>", "<body style=\"margin:0;padding:0;\">");
return "<!DOCTYPE html>\n" + htmlAdded;
}