如何在webview中设置自定义字体

本文将指导您如何在Android应用中,将自定义字体文件(.otf格式)放入assets文件夹,并创建HTML文件以在WebView中显示。包括在HTML中注入CSS样式以实现字体替换,以及如何从代码中加载这个HTML页面到WebView。注意,此方法仅适用于.otf格式的字体,不支持.ttf格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


  • In your assets/fonts folder, place the desired OTF or TTF font (here MyFont.otf)
  • Create a HTML file that you'll use for the WebView's content, inside the assets folder (here insideassets/demo/my_page.html):
    <html>
    <head>
    <style type="text/css">
    @font-face {
        
    font-family: MyFont;
        
    src: url("file:///android_asset/fonts/MyFont.otf")
    }
    body 
    {
        
    font-family: MyFont;
        
    font-size: medium;
        
    text-align: justify;
    }
    </style>
    </head>
    <body>
    Your text can go here! Your text can go here! Your text can go here!
    </body>
    </html>
  • Load the HTML into the WebView from code:
    webview.loadUrl("file:///android_asset/demo/my_page.html");

Take note that injecting the HTML through loadData() has not worked for me. I'd be curious to hear if anybody can get that working.

需要注意的是,这种方式,只能使用.otf格式的字体文件,不能使用ttf格式的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值