2012년 10월 5일 금요일

[Java/Android] DIP to Pixel, Pixel to DIP 변환 ..



dp, px 에 관한 참고 : http://cafe.naver.com/mgui/2197

참고 : http://theeye.pe.kr/entry/display-utility-for-convert-dip-to-pixel-on-android

안드로이드에서는 기본적으로 화면 해상도에 의존적이지 않는 화면 구성을 하여야만 합니다. 하지만 동적으로 UI를 구축한다거나 또는 복잡한 레이아웃에서는 그것이 쉽지가 않죠. 그경우엔 픽셀 단위의 글을 자유자재로 DIP으로 혹은 그 반대로 변환할 수 있어야 합니다. 다음은 간단히 사용할 수 있는 예제입니다.

public class DisplayUtil
{
  private static final float DEFAULT_HDIP_DENSITY_SCALE = 1.5f;
  /**
   * 픽셀단위를 현재 디스플레이 화면에 비례한 크기로 반환합니다.
   * 
   * @param pixel 픽셀
   * @return 변환된 값 (DP)
   */
  public static int DPFromPixel(int pixel)
  {
    Context context = BaseApplication.getContext();
    float scale = context.getResources().getDisplayMetrics().density;
    
    return (int)(pixel / DEFAULT_HDIP_DENSITY_SCALE * scale);
  }
  
  /**
   * 현재 디스플레이 화면에 비례한 DP단위를 픽셀 크기로 반환합니다.
   * 
   * @param  DP 픽셀
   * @return 변환된 값 (pixel)
   */
  public static int PixelFromDP(int DP)
  {
    Context context = BaseApplication.getContext();
    float scale = context.getResources().getDisplayMetrics().density;
    
    return (int)(DP / scale * DEFAULT_HDIP_DENSITY_SCALE);
  }
}

댓글 없음:

댓글 쓰기