Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
screenWidthDpちょっと 怖いかも、、??
Search
takarabe-hamuyatti
December 02, 2023
0
270
screenWidthDpちょっと 怖いかも、、??
dpとかpxに関する話です。
takarabe-hamuyatti
December 02, 2023
Tweet
Share
More Decks by takarabe-hamuyatti
See All by takarabe-hamuyatti
Gradle超入門 / Gradle Super Beginner's Guide"
rabeyatti
0
540
Performance Classを触ってみよう
rabeyatti
0
280
Featured
See All Featured
4 Signs Your Business is Dying
shpigford
176
21k
How GitHub Uses GitHub to Build GitHub
holman
468
290k
Let's Do A Bunch of Simple Stuff to Make Websites Faster
chriscoyier
501
140k
Unsuck your backbone
ammeep
663
57k
I Don’t Have Time: Getting Over the Fear to Launch Your Podcast
jcasabona
22
1.6k
Ruby is Unlike a Banana
tanoku
96
10k
Visualizing Your Data: Incorporating Mongo into Loggly Infrastructure
mongodb
34
8.9k
Exploring the Power of Turbo Streams & Action Cable | RailsConf2023
kevinliebholz
7
3.4k
RailsConf 2023
tenderlove
8
550
BBQ
matthewcrist
80
8.8k
Into the Great Unknown - MozCon
thekraken
14
1k
Why Our Code Smells
bkeepers
PRO
331
56k
Transcript
screenWidthDpちょっと 怖いかも、、??
目次 • 自己紹介 • 結論 • 基礎知識 • screenWidthDpについて •
何が落とし穴? • screenWidthDpをもとにpxを作ると? • 改めて結論
自己紹介 財部彰太 twitter : rabe_hamuyatti 株式会社ZOZO 2023新卒 ZOZOTOWNのAndroidアプリを作って います。 旅行とか、服とか、音楽が好きです。
結論 画面幅をpxの単位でほしい時は、Configuration.screenWidthDpをpxに変換すると正 確な値が取れない。 BoxWithConstraintsScope.maxWidthにtoPxをかけたもの または Resources.getSystem().displayMetrics.width を使おう。
基礎知識 px → デジタル画像の最小単位。 dpi(dot per inch) → 1インチあたりのドット数。画面密度 dp(density-independent
pixels) → 密度非依存ピクセル。dpが端末の画面密度に応じてpxに変換され、ユーザーの目に 届く。
screenWidthDpについて dp単位で表示可能な画面領域の幅のこと。(WindowInsetを除いた値) 取得方法 • Resources.getSystem().configuration.screenWidthDp • LocalConfiguration.current.screenWidthDp 公式Document https://developer.android.com/reference/android/content/res/Configuration#screenWidthDp
何が落とし穴? Floatではなく、Intで保存されていること (BoxWithConstraintsScope.maxWidthはFloat) DPを求める式は 画面幅(px) * 160 / dpi →
割り切れなさそうじゃない、、?? 計算式 https://developer.android.com/training/multiscreen/screendensities?hl=ja#dips-pels screenWidthDpの実際のコード https://cs.android.com/android/platform/superproject/+/master:frameworks/base/core/java/android/content/res/Configurat
何が落とし穴? 実際、Pixel6では 横幅 → 1080px dpi → 420 1080 *
160 / 420 = 411.4285 → ScreenWidthDpはIntのため、端数が切り落とされ411で保存されている 公式Document https://developer.android.com/reference/android/content/res/Configuration#screenWidthDp
screenWidthDpをもとにpxを作ると? LocalConfiguration.current.screenWidthDp.dp.toPx() や Resources.getSystem().configuration.screenWidthDp * resources.displayMetrics.densityDpi / 160 → 1078.875
本来の1080とずれてしまっている!!!
改めて。 px単位で正確な画面横幅を知りたいときは Resources.getSystem().displayMetrics.widthPixels BoxWithConstraintsScope.maxWidthをpxに変換 を使いましょう。(他にもあるかも?)
おしまい!