Using custom fonts in WKWebView

后端 未结 5 573
栀梦
栀梦 2020-11-29 00:15

I\'m using custom fonts in my app. They are copied to bundle and hardcoded to appName-info.plist. This fonts works perfectly in the whole app and in UIWebView.

Im lo

5条回答
  •  没有蜡笔的小新
    2020-11-29 00:54

    Since I don't want to use another third party just for that and since I'm building the html string itself, I took the first part of using the font-face and instead of using a url to a remote or local file, i converted the fonts to base64.

    The css looks like this:

    @font-face {
        font-family: 'FONTFAMILY';
        src: url(data:font/ttf;base64,FONTBASE64) format('truetype');
    }
    

    You can replace the FONTFAMILY with the family that you need and the FONTBASE64 with the base 64 string that was generated from the font.

    If you need to create the base64 string in your application, you can use this, just provide the filename and type (i used it to get other files as well so it's more generic, you can remove the ofType parameter and use @"ttf" instead):

    - (NSString*)getBase64FromFile:(NSString*)fileName ofType:(NSString*)type
    {
        NSString * filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:type];
    
        // Create NSData object
        NSData *nsdata = [NSData dataWithContentsOfFile:filePath];
    
        // Get NSString from NSData object in Base64
        NSString *base64Encoded = [nsdata base64EncodedStringWithOptions:0];
    
        return base64Encoded;
    }
    

    if you want to do it only one time and then save it in some file, you can use any of the online websites that converts files to base64, like this: http://www.opinionatedgeek.com/dotnet/tools/base64encode/

提交回复
热议问题