UIWebView中的字体大小与iOS字体大小不匹配

时间:2016-07-05 12:15:40

标签: ios css uiwebview retina-display

这是一个说“关于”的UILabel。在iOS中设置为17.7。

在它下面是一个UIWebView,它也说“关于”。使用css也设置为17.7。

enter image description here

他们不匹配。

如何正确解决这个问题?

在Apple自己的UIWebView中,奇怪,大小基础不同

要测试的HTML ...

<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>

设备或模拟器上的行为相同。

(注意,从here我得知这个比例可能是72.0 / 96.0。)

3 个答案:

答案 0 :(得分:14)

If you want a 1 to 1 relationship between the font size that the UILabel uses and the font size that the UIWebView uses (via CSS) you have to use px instead of pt when defining the font size in your CSS.

Checkout this example 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>

When you add a UIWebView and a UILabel to your UIViewController and load the above HTML to the UIWebView and set the same font to the 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)
}

You get the following output:

enter image description here

答案 1 :(得分:0)

我认为你的困惑是因为CSS pt是一个印刷点(1/72英寸),但Apple的iOS文档使用“点”(例如UIFont.pointSize)作为“虚拟像素”,它对应于CSS px。从@ joern的回答来看,看起来UIWebView使用1 css px = 1 ios virtual px。 (我没有测试过这个。)但是,在我使用WKWebView的测试中,看起来CSS px等于一个设备像素。因此,对于WKWebView,您需要:

let fontSize = UIScreen.main.scale * label.font.pointSize
let cssStr = String(format:"font-size: %.1fpx;", fontSize)

答案 2 :(得分:-3)

是的,它是父字体大小的问题:

您应该始终将body的font-size设置为16px(如果需要更大的基本字体,则可以将其设置得更高,标准为16px)。

然后,使用16px作为基础设置字体大小。

body {
    font-size: 16px;
}

h1 {
    font-size: 24px;
}

如果你想要正文和h1字体大小相同,那么只需设置正文字体大小,不要设置h1的字体大小(它将继承正文字体大小)所有这一切... ... ...级联)。

body {
    font-size: 16px;
}

h1 {

}

你所做的是将body font-size设置为一个值...然后将h1 font-size设置为相同的值,问题是h1从body继承font-size然后更大你将字体大小分配给h1。

希望这是有道理和有帮助的。