2012-05-07 71 views
48

我想在UIWebView中顯示自定義字體。我已經將字體放在「應用程序提供的字體」下的plist中。使用代碼:在UIWebView中使用自定義字體

 UIWebView *webView = [[UIWebView alloc] initWithFrame:myRect]; 
     NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]; 
     [webView loadHTMLString:html baseURL:baseURL]; 
     [self addSubview:webView]; 

其中HTML是具有下列內容一個NSString:

<html><head> 
<style type="text/css"> 
@font-face { 
    font-family: gotham_symbol; 
    src: local('GOTHAMboldSymbol_0.tff'), format('truetype') 
} 
body { 
font-family: gotham_symbol; 
font-size: 50pt; 
} 
</style> 
</head><body leftmargin="0" topmargin="0"> 
This is <i>italic</i> and this is <b>bold</b> and this is some unicode: &#1101; 
</body></html> 

我使用的是iOS 4.2所以TTF應予以支持。我會欣賞一些實際可行的html /代碼。

+1

'GOTHAMboldSymbol_0.tff' - 擴展應該是' ttf'(除非字體在磁盤上確實有'tff'擴展名)。 –

+0

我試圖找到一個解決方案,但是:我想你想通過baseURL'零'。 – MusiGenesis

+0

@Joris我現在正面臨同樣的問題,如果您找到了解決方案,聽聽會很有趣。 – Lindemann

回答

93

一些嘗試後和錯誤我已經找到了一個可靠的方式來加載自定義的字體與當地的CSS。

1.添加你的字體到App ...確保該文件是針對 正確的應用

enter image description here enter image description here

2.添加您的字體來yourApp-Info.plist中

enter image description here

3.運行NSLog(@"Available fonts: %@", [UIFont familyNames]);要檢查其名稱的字體/ fontFamily中先後爲SYSTE米...

enter image description here

4.複製該名稱,並利用它們在你的CSS ... @不需要字體面

body { 
    font-family:"Liberation Serif"; 
} 
+0

對不起,我包括那一步。我曾以某種方式假定你已經完成了這一步... –

+0

謝謝!這是記錄在任何地方? – ozz

+4

步驟1-3基本上是嚮應用程序添加自定義字體的標準方式...所以是的,它被記錄。在最後一步中,您使用調用系統上可用字體的標準方式...... :-) – Lindemann

10

我最終使它工作,雖然我不知道我上面做錯了什麼。這裏是我使用的HTML(NSString * htmll)。我添加了所有內容,其中一些可能與解決方案無關。

<html><head><style type="text/css"> 
@font-face { 
font-family: 'gotham_symbol'; 
src: url('GOTHAMboldSymbols_0.ttf') format('truetype') 
} 
@font-face { 
font-family: 'gotham_symbol_italic'; 
src: url('GothamBoldItalic.ttf') format('truetype') 
} 
#w {display:table;} 
#c {display:table-cell; vertical-align:middle;} 
i { font-family: 'Helvetica-BoldOblique'; } 
</style></head><body topmargin="0" leftmargin="0"> 
<div style="display: table; width: 320px; height: 50px; #position: relative; overflow: hidden;"> 
<div style=" #position: absolute; #top: 50%;display: table-cell; vertical-align: middle;"> 
<div style=" #position: relative; #top: -50%"> 
<p style="font-size:20px;font-family:'gotham_symbol';color:#97371f;">THE TEXT GOES HERE</p></div></div></div></body></html> 

和我加載的UIWebView如下:

UIWebView *webView = [[UIWebView alloc] initWithFrame:rect]; 
[webView makeTransparent]; 
NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]; 
[webView loadHTMLString:html baseURL:baseURL]; 
+0

謝謝Joris! <3 – Lindemann