設計稿多半用 px 標註,而 iOS 開發時寫的是 pt。這兩個單位到底怎麼換?本文把常見的換算關係整理成對照表,方便隨時查閱。
換算公式:
pt = (px / 96) * 72
換句話說,1pt 在 96 DPI 的基準下大約等於 1.333 px;而 iOS 的 @2x、@3x 螢幕會再把 1pt 分別放大成 2 與 3 個實體像素。
先記住這組基準換算:1 in = 2.54 cm = 25.4 mm = 72 pt = 6 pc。
| Points | Pixels | Ems | Percent |
|---|---|---|---|
| 6pt | 8px | 0.5em | 50% |
| 7pt | 9px | 0.55em | 55% |
| 7.5pt | 10px | 0.625em | 62.5% |
| 8pt | 11px | 0.7em | 70% |
| 9pt | 12px | 0.75em | 75% |
| 10pt | 13px | 0.8em | 80% |
| 10.5pt | 14px | 0.875em | 87.5% |
| 11pt | 15px | 0.95em | 95% |
| 12pt | 16px | 1em | 100% |
| 13pt | 17px | 1.05em | 105% |
| 13.5pt | 18px | 1.125em | 112.5% |
| 14pt | 19px | 1.2em | 120% |
| 14.5pt | 20px | 1.25em | 125% |
| 15pt | 21px | 1.3em | 130% |
| 16pt | 22px | 1.4em | 140% |
| 17pt | 23px | 1.45em | 145% |
| 18pt | 24px | 1.5em | 150% |
| 20pt | 26px | 1.6em | 160% |
| 22pt | 29px | 1.8em | 180% |
| 24pt | 32px | 2em | 200% |
| 26pt | 35px | 2.2em | 220% |
| 27pt | 36px | 2.25em | 225% |
| 28pt | 37px | 2.3em | 230% |
| 29pt | 38px | 2.35em | 235% |
| 30pt | 40px | 2.45em | 245% |
| 32pt | 42px | 2.55em | 255% |
| 34pt | 45px | 2.75em | 275% |
| 36pt | 48px | 3em | 300% |
要在實體尺寸與像素之間轉換,還需要知道 DPI(每英寸有多少點):
像素數 / DPI = 英寸數 英寸數 × 25.4 = 毫米數
無論是印表機還是螢幕,都可以透過系統 API 取得該裝置每英寸的像素數(在 Windows 上是以 GetDeviceCaps 搭配 LOGPIXELSX/LOGPIXELSY 取得,分別記為 px 與 py)。既然 1 英寸等於 25.4 mm,換算公式就是:
水平方向:x × px / 25.4 垂直方向:y × py / 25.4 反過來(像素轉毫米):x × 25.4 / px
程式中的寫法可以像這樣:
MyControl.Height := 10 {mm} * PixelsPerInch * 10 div 254;
分子分母同乘 10,把浮點運算轉成整數運算,效率會更好。
至於 1024×768、800×600 這類標準解析度,算出來的 DPI 是一個固定值 96,因此毫米與像素之間也趨近一個常數:1 毫米約等於 3.78 像素。