UIWebView中的字体大小不符合iOS字体大小
这是一个说“关于”的UILabel。 在iOS中精确设置为17.7。
在它下面还有一个UIWebView,它也说“关于”。 也使用css精确设置为17.7。
他们不匹配。
如何正确解决这个问题?
奇怪的是,在苹果自己的UIWebView,大小的基础是不同的 ?
Html来testing…
<html><head> <style type='text/css'> body { margin: 0px; font-family: 'SourceSansPro-Light'; font-size: FONTPOINTSpt; } html { -webkit-text-size-adjust:none; } </style></head> <body leftmargin=0 topmargin=0> About </body></html>
行为在设备或模拟器上是相同的。
(注意,从这里我知道这个比例是72.0 / 96.0。)
如果你想在UILabel
使用的字体大小和UIWebView
使用的字体大小(通过CSS)之间有1对1的关系,那么当你在CSS中定义字体大小时,你必须使用px
来代替pt
。
结帐这个例子HTML / CSS:
<html> <head> <style type='text/css'> body { font-family: 'SourceSansPro-Regular'; padding: 0 } .point { font-size: 17pt } .pixel { font-size: 17px } </style> </head> <body> <p class="point">About (17pt)<p> <p class="pixel">About (17px)</p> </body> </html>
当你添加一个UIWebView
和一个UILabel
到你的UIViewController
并加载上面的HTML到UIWebView
并设置相同的字体到UILabel
:
override func viewDidLoad() { super.viewDidLoad() let webView = UIWebView(frame: CGRect(x: 25, y: 50, width:325 , height: 90)) view.addSubview(webView) let filePath = NSBundle.mainBundle().URLForResource("test", withExtension: "html") webView.loadRequest(NSURLRequest(URL: filePath!)) let label = UILabel(frame: CGRect(x: 25, y: 150, width: 325, height: 40)) label.font = UIFont(name: "SourceSansPro-Regular", size: 17) label.text = "About (UILabel set to 17)" view.addSubview(label) }
你得到以下输出:
我认为你的困惑是因为CSS pt是一个印刷点(1/72英寸),但是苹果的iOS文档使用“点”(例如UIFont.pointSize)作为“虚拟像素”,这对应于CSS px。 从@ joern的回答来看,它看起来像UIWebView使用1 css px = 1 ios虚拟PX。 (我没有testing过这个)。但是,在我的WKWebViewtesting中,它看起来像CSS px等于一个设备像素。 所以对于WKWebView,你需要:
let fontSize = UIScreen.main.scale * label.font.pointSize let cssStr = String(format:"font-size: %.1fpx;", fontSize)
是的,它的父字体大小的问题:
您应该始终将body的font-size设置为16px(如果需要更大的基本字体,则可以将其设置得更高,标准为16px)。
然后,使用16px作为基础设置字体大小。
body { font-size: 16px; } h1 { font-size: 24px; }
如果你希望body和h1字体大小相同,那么简单地设置body的font-size并且不要设置h1的font-size(它会自动inheritancebody的font-size)。 ..又名…级联)。
body { font-size: 16px; } h1 { }
你所做的是将body font-size设置为一个值…然后将h1 font-size设置为相同的值,问题是h1从bodyinheritance字体大小,然后在分配字体大小为h1。
希望这是有道理的,并帮助。