2014-12-04 56 views
2

我使用WebView来呈现某些html内容。在我的CSS,我有以下代码:Lollipop中的WebView不会从资产中加载字体

@font-face { 
    font-family: CharterC; 
    font-style: normal; 
    font-weight: normal; 
    src: url("asset://fonts/CharterC.otf"); 
} 

而且我在WebViewClient下面的Java代码:

@Override 
public WebResourceResponse shouldInterceptRequest(WebView view, String url) { 
    if (url.startsWith(ASSETS_SCHEME)) { 
     String asset = url.substring(ASSETS_SCHEME.length()); 
     if (asset.endsWith(".js")) { 
      try { 
       return new WebResourceResponse("text/javascript", "utf-8", context.getAssets().open(asset)); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } else if (asset.endsWith(".ttf") || asset.endsWith(".otf")) { 
      try { 
       return new WebResourceResponse("font/" + MimeTypeMap.getFileExtensionFromUrl(asset), "utf-8", context.getAssets().open(asset)); // this will produce MimeType like: font/ttf 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

而且此代码的​​工作相当不错,在Android的4.1-4.4,但在Android的5.0此代码加载JS,但无法加载字体,和我看到的WebKit控制台以下消息:

从原产字体的资产://“已经加载由 跨域资源受阻共享策略:没有“访问控制 - 允许来源” 标题出现在请求的资源上。原因'null'是 ,因此不允许访问。

如何从Android 5.0资产加载字体?

回答

4

您需要使用新的WebResourceResponse构造函数来设置HTTP头与截取的请求一起传递。

由于新的构造函数仅在Lollipop中引入,请务必在运行时检查SDK版本。

InputStream inputStream = context.getAssets().open("fonts/myfontasset.ttf"); 
WebResourceResponse response = null; 
String encoding= "UTF-8"; 
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 
    int statusCode = 200; 
    String reasonPhase = "OK"; 
    Map<String, String> responseHeaders = new HashMap<String, String>(); 
    responseHeaders.put("Access-Control-Allow-Origin","*"); 
    response = new WebResourceResponse("font/ttf", encoding, statusCode, reasonPhase, responseHeaders, inputStream); 
} else { 
    response = new WebResourceResponse("font/ttf", encoding, inputStream); 
} 

注意:您必须至少构建SDK级别21。