2011-12-06 3 views
46

딥에서 픽셀을 가져 오는 메소드를 작성했지만 작동하지 않습니다. 런타임 오류가 발생합니다. 안드로이드에서 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); 
} 

희망 ...

123

이 시도 :

자바

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

코 틀린를

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

픽셀에 대해 float로 무엇을 반환 하시겠습니까? int에 캐스트하면 안 되는가? – hjchin

+0

작동하지만, 내 부동 활동에 승, h를 적용하는 것, 안드로이드는 오른쪽과 왼쪽 (총 32dp)에 16dp를 추가합니다. 거기에있는 dipValue는 레이아웃 xml + 32dp에있는 dipValue입니다. – Mercury

34

을 당신은 dimen.xml의 DP 값을 추가하고

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

그것은 쉽게 ...

을 사용할 수 있습니다
0

시도해보기 : 컨텍스트를 전달하지 않고 사용하기 위해

public static float dipToPixels(float dipValue) { 
     return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, Resources.getSystem().getDisplayMetrics()); 
    } 
관련 문제