I have a UIWebView and I have a custom font I want to load into an editable html document that I will be displaying through the UIWebView. In my SupportingFiles (resources) folder I have "Nosifer-Regular.ttf"... To use the custom font in my HTML I need the path (URL) to the font tile... I tried doing this, but it didn't seem to work... any ideas?
bundle = [NSBundle mainBundle];
pathFont = [bundle bundlePath];
fontURL = [NSBundle pathForResource:@"Nosifer-Regular" ofType:@"ttf" inDirectory:pathFont];
path_font = [fontURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
fileAppend = [[NSString alloc] initWithFormat:@"file://"];
path_font = [[NSString alloc] initWithFormat:@"%@%@", fileAppend, path_font];
The HTML (CSS):
@font-face {
font-family: 'Nosifer';
font-style: normal;
font-weight: 400;
src: local('Nosifer'), local('Nosifer-Regular'), url('%@') format('truetype');
}
Where %@ is replaced with "path_font" (defined above in the first code block)
First of all, add filed "Fonts provided by application" in your info.plist
. It will be an array like
item0 myFont.otf
item1 anotherFont.ttf
or something.
In HTML use font-face to add a font. And place your font files in the same directory with html file. If HTML is generated dynamically and not shown from bundle then you should copy font .
Good luck.
I got a working html code example here.
<html>
<head>
<style type='text/css'>
p.p1 {margin: 0.0px 0.0px 0.0px 30.0px; font: 34.0px;}
@font-face {
font-family: 'Nosifer'; font-style: normal; font-weight: 400; src: local('Nosifer'), local('Nosifer-Regular'), url('Nosifer-Regular.ttf') format('truetype');
}
.nosifer {
font-family: Nosifer;
}
</style>
</head>
<body allowtransparency='true'>
<p class="nosifer">Nosifer ABCabc</p>
</body>
As you can see I used a css class to define the font more easily. I'm not sure what all that CSS code within font-face means, but it seems to work.
I confirmed that you NEED to add "Nosifer-Regular.ttf" to the array of fonts provided by the application in the *-info.plist file (key: Fonts provided by application). Btw I googled Nosifer-Regular.ttf and found it on a noisy site here. It really worked though: http://www.ffonts.net/Nosifer.font.download
Then, I was also able to load an OTF that I'll be using in my case. In the CSS I changed format from truetype to opentype.
Add your custom font in your project. Then
Get font name
UIFont *font = [UIFont fontWithName:@"Your-Custom-font" size:20];
Then create html string
NSString *htmlHeader=[NSString stringWithFormat:@"<html><head><head><link rel=\"stylesheet\" type=\"text/css\" href=\"file://localhost%@\"></head><body><font face=\"%@\"; size=\"4\">HI</font></body></html>",cssPath,font.familyName];
Good luck.
Here is how you'd add the font to your Info.plist:
<key>UIAppFonts</key>
<array>
<string>Nosifer-Regular.ttf</string>
</array>
Then use @font-face as per this other answer.
来源:https://stackoverflow.com/questions/9014211/ios-custom-font-path-for-uiwebviews