2011-12-06 15 views
46

ディップからピクセルを取得する方法を書いていましたが、機能しません。それは私にランタイムエラーを与える。私のActivityクラスでAndroidでdipをpxに変換する

実は、私は別のクラスでこのメソッドを実行し、初期化された

Board board = new Board(this); 
board.execute(URL); 

非同期に実行します。このコード。私を助けてください。

public float getpixels(int dp){ 

     //Resources r = boardContext.getResources(); 
     //float px = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpis, r.getDisplayMetrics()); 

     final float scale = this.boardContext.getResources().getDisplayMetrics().density; 
      int px = (int) (dp * scale + 0.5f); 



     return px; 

    } 
+0

どのようなエラーが発生しますか? boardContextがnullですか? getResourcesはnullですか? – Sulthan

答えて

14

式は:PX = DP *(DPI/160)、160 DPIに有するため画面。詳細については、http://developer.android.com/guide/practices/screens_support.htmlを参照してください。

あなたは試みることができる:

public static int convertDipToPixels(float dips) 
{ 
    return (int) (dips * appContext.getResources().getDisplayMetrics().density + 0.5f); 
} 

・ホープこれはあなたがdimen.xmlにDP値を追加し、それは簡単だ

int pixels = getResources().getDimensionPixelSize(R.dimen.idDimension); 

を使用することができます...

123

これを試してください:

ジャワ

public static float dipToPixels(Context context, float dipValue) { 
    DisplayMetrics metrics = context.getResources().getDisplayMetrics(); 
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics); 
} 

Kotlin

fun Context.dipToPixels(dipValue: Float) = 
    TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, resources.displayMetrics) 
+5

ピクセルのために何を返すでしょうか? intにキャストすべきではありませんか? – hjchin

+0

動作していますが、私のフローティングアクティビティにw、hを適用したようです。アンドロイドは16dpを左右に(合計32dp)追加します。そこにあるdipValueは、レイアウトxml + 32dpにあるdipValueです。 – Mercury

0

これを試してください:コンテキストを渡さずに

public static float dipToPixels(float dipValue) { 
     return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, Resources.getSystem().getDisplayMetrics()); 
    } 
関連する問題