46
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

dp↔px変換サンプルコード

Last updated at Posted at 2016-03-31

そのものずばりのサンプルコードがQiita上にはないようだったのと、詳しい記事ばかりでさくっとサンプルが欲しかったので。

dpの説明は詳しい記事があるのでそちらをどうぞ。
【Android】いまさら聞けないdp入門
Y.A.M の 雑記帳: Android dip, dp, から pt, px に変換する

サンプルコード

端末の解像度を取ってきて計算してるだけです。
(pixelの返却値がfloatなので使うときはキャストしてどうぞ)

/**
 * dpからpixelへの変換
 * @param dp
 * @param context
 * @return float pixel
 */
public static float convertDp2Px(float dp, Context context){
    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    return dp * metrics.density;
}

/**
 * pixelからdpへの変換
 * @param px
 * @param context
 * @return float dp
 */
public static float convertPx2Dp(int px, Context context){
    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    return px / metrics.density;
}
46
33
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
46
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?