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

Font sizes in UIWebView does NOT match iOS font size

这是一个显示 "About" 的 UILabel。在 iOS.

中精确设置为 17.7

在它下面是一个 UIWebView,它也显示 "About"。还使用 css.

精确设置为 17.7

它们不匹配。

如何正确解决这个问题?

很奇怪Apple自带的UIWebView中,size basis不一样?

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

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

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

然后,设置字体大小以16px为底。

body {
    font-size: 16px;
}

h1 {
    font-size: 24px;
}

如果您希望 body 和 h1 的字体大小相同,则只需设置 body 字体大小而不设置 h1 的字体大小(它将继承 body 字体大小全部靠自己......又名......级联)。

body {
    font-size: 16px;
}

h1 {

}

你所做的是将 body 字体大小设置为一个值...然后将 h1 字体大小设置为相同的值,问题是 h1 继承了 body 的字体大小然后变得均匀将字体大小分配给 h1 时更大。

希望这是有道理的并有所帮助。

如果您希望 UILabel 使用的字体大小与 UIWebView 使用的字体大小(通过 CSS)之间存在一对一的关系,您必须使用 px 而不是 pt 在 CSS.

中定义字体大小时

查看此示例 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>

当您将 UIWebViewUILabel 添加到 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 英寸),但 Apple 的 iOS 文档使用 "point"(例如 UIFont.pointSize)作为 "virtual pixel",对应于 CSS 像素。从@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)