Android에서 Webview의 글꼴을 변경하는 방법은 무엇입니까? 앱을 개발하는

webview의 기본 글꼴을 사용자 정의 글꼴로 변경하고 싶습니다. Android 용 이중 언어 브라우저 앱을 개발하는 데 webview를 사용하고 있습니다.

사용자 지정 글꼴을 자산에 배치하여 사용자 지정 서체의 인스턴스를 얻으려고했습니다. 하지만 여전히 webview의 기본 글꼴을 내 글꼴로 설정할 수 없습니다.

이것이 내가 시도한 것입니다.

Typeface font = Typeface.createFromAsset(getAssets(), "myfont.ttf");
private WebView webview;
WebSettings webSettings = webView.getSettings();
webSettings.setFixedFontFamily(font);

누구나 이것을 수정하거나 webview의 기본 글꼴을 사용자 정의 글꼴로 변경하는 다른 방법을 제안 할 수 있습니까?

감사!



답변

이 프로젝트 에는 이에 대한 실제적인 예가 있습니다. 요약하면 다음과 같습니다.

  1. 당신에 assets/fonts폴더 (여기 MyFont.otf) 원하는 OTF 또는 TTF 폰트를 배치
  2. assets폴더 안에 WebView의 콘텐츠에 사용할 HTML 파일을 만듭니다 (여기 내부 assets/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>
  3. 코드에서 WebView로 HTML을로드합니다.

    webview.loadUrl("file:///android_asset/demo/my_page.html");

HTML을 통해 삽입하는 loadData()것은 허용되지 않습니다. 문서에 따라 :

JavaScript의 동일한 출처 정책은이 방법을 사용하여로드 된 페이지에서 실행되는 스크립트가 ‘http (s)’를 포함하여 ‘data’이외의 스키마를 사용하여로드 된 콘텐츠에 액세스 할 수 없음을 의미합니다. 이 제한을 피하려면 적절한 기본 URL과 함께 loadDataWithBaseURL ()을 사용하십시오.

@JaakL이 아래 주석에서 제안했듯이 문자열에서 HTML을로드하려면 대신 자산을 가리키는 기본 URL을 제공해야합니다.

webView.loadDataWithBaseURL("file:///android_asset/", htmlData);

에서 글꼴을 참조 할 때 htmlData간단히 사용할 수 있습니다 /fonts/MyFont.otf(기본 URL 생략).


답변

이 코드를 사용하고 있습니다 .

wv = (WebView) findViewById(R.id.webView1);
String pish = "<html><head><style type=\"text/css\">@font-face {font-family: MyFont;src: url(\"file:///android_asset/font/BMitra.ttf\")}body {font-family: MyFont;font-size: medium;text-align: justify;}</style></head><body>";
String pas = "</body></html>";
String myHtmlString = pish + YourTxext + pas;
wv.loadDataWithBaseURL(null,myHtmlString, "text/html", "UTF-8", null);


답변

더 간단하게 자산 URL 형식을 사용하여 글꼴을 참조 할 수 있습니다. 프로그래밍이 필요하지 않습니다!

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

body {
   font-family: 'myface', serif;


답변

Android에서 할 수 있습니다. 이 문제를 해결하는 데 3 일이 걸렸습니다. 그러나 이제는 매우 쉬워 보입니다. Webview에 대한 사용자 정의 글꼴을 설정하려면 다음 단계를 따르십시오.

1. 자산 폴더
에 글꼴 추가 2. 응용 프로그램의 파일 디렉터리에 글꼴 복사

private boolean copyFile(Context context,String fileName) {
        boolean status = false;
        try {
            FileOutputStream out = context.openFileOutput(fileName, Context.MODE_PRIVATE);
            InputStream in = context.getAssets().open(fileName);
            // Transfer bytes from the input file to the output file
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            // Close the streams
            out.close();
            in.close();
            status = true;
        } catch (Exception e) {
            System.out.println("Exception in copyFile:: "+e.getMessage());
            status = false;
        }
        System.out.println("copyFile Status:: "+status);
        return status;
    }

3. 위의 함수는 한 번만 호출해야합니다 (이에 대한 논리를 찾아야합니다).

copyFile(getContext(), "myfont.ttf");

4. 아래 코드를 사용하여 webview에 대한 값을 설정하십시오. 여기에서는 CSS를 사용하여 글꼴을 설정하고 있습니다.

private String getHtmlData(Context context, String data){
    String head = "<head><style>@font-face {font-family: 'verdana';src: url('file://"+ context.getFilesDir().getAbsolutePath()+ "/verdana.ttf');}body {font-family: 'verdana';}</style></head>";
    String htmlData= "<html>"+head+"<body>"+data+"</body></html>" ;
    return htmlData;
 }

5. 위 함수를 아래와 같이 호출 할 수 있습니다.

webview.loadDataWithBaseURL(null, getHtmlData(activity,htmlData) , "text/html", "utf-8", "about:blank");


답변

나는이 추가 사항으로 상위 답변으로 이것을 수행했습니다.

webView.loadDataWithBaseURL("file:///android_asset/",
                            WebClient.getStyledFont(someText),
                            "text/html; charset=UTF-8", null, "about:blank");

그런 다음 src: url("file:///android_asset/fonts/YourFont...

public static String getStyledFont(String html) {
    boolean addBodyStart = !html.toLowerCase().contains("<body>");
    boolean addBodyEnd = !html.toLowerCase().contains("</body");
    return "<style type=\"text/css\">@font-face {font-family: CustomFont;" +
            "src: url(\"file:///android_asset/fonts/Brandon_reg.otf\")}" +
            "body {font-family: CustomFont;font-size: medium;text-align: justify;}</style>" +
            (addBodyStart ? "<body>" : "") + html + (addBodyEnd ? "</body>" : "");
}

모두에게 감사드립니다 🙂


답변

위의 답변 중 대부분은 자산 폴더에 콘텐츠가 있으면 매력적입니다.

그러나 저를 좋아한다면 서버에서 내부 저장소로 모든 자산을 다운로드하고 저장하려면 대신 내부 저장소에 loadDataWithBaseURL대한 참조를 baseUrl로 사용 하고 사용할 수 있습니다 . 그런 다음 거기에있는 모든 파일은로드 된 html에 상대적이며 올바르게 찾고 사용됩니다.

내 내부 저장소에 다음 파일을 저장했습니다.

  • IndigoAntiqua2Text-Regular.ttf
  • style.css
  • image.png

그런 다음 다음 코드를 사용합니다.

WebView web = (WebView)findViewById(R.id.webby);
//For avoiding a weird error message
web.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

String webContent = "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><link rel=\"stylesheet\" href=\"style.css\"></head>"
                            + "<body><img src='image.png' width=\"100px\"><div class=\"running\">I am a text rendered with INDIGO</div></body></html>";

String internalFilePath = "file://" + getFilesDir().getAbsolutePath() + "/";
web.loadDataWithBaseURL(internalFilePath, webContent, "text/html", "UTF-8", "");

위의 html (style.css)에서 사용 된 CSS 파일 :

@font-face {
  font-family: 'MyCustomRunning';
  src: url('IndigoAntiqua2Text-Regular.ttf')  format('truetype');
}

.running{
    color: #565656;
     font-family: "MyCustomRunning";
     font-size: 48px;
}

minSdkVersion 19 (4.4)를 대상으로하는 동안에 만 이것을 시도 했으므로 다른 버전에서 작동하는지 모르겠습니다.


답변

 webview= (WebView) findViewById(R.id.webview);
 String myCustomStyleString="<style type=\"text/css\">@font-face {font-family: MyFont;src: url(\"file:///android_asset/fonts/iranian_sans.ttf\")}body,* {font-family: MyFont; font-size: 13px;text-align: justify;}img{max-width:100%;height:auto; border-radius: 8px;}</style>";
 webview.loadDataWithBaseURL("", myCustomStyleString+"<div style=\"direction:rtl\">"+intentpost.getStringExtra("content")+"</div>", "text/html", "utf-8", null);