Media Log

pixel과 dp를 자연스럽게 바꿀 수 있는 코드입니다.


예를 들어 이미지를 코드로 넣을 경우 매우 유용하게 사용될 것입니다. ^^


    /**

    * This method converts dp unit to equivalent pixels, depending on device density.

    *

    * @param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels

    * @param context Context to get resources and device specific display metrics

    * @return A float value to represent px equivalent to dp depending on device density

    */

    public static float convertDpToPixel(float dp, Context context){

        Resources resources = context.getResources();

        DisplayMetrics metrics = resources.getDisplayMetrics();

        float px = dp * (metrics.densityDpi / 160f);

        return px;

    }

 

    /**

     * This method converts device specific pixels to density independent pixels.

     *

     * @param px A value in px (pixels) unit. Which we need to convert into db

     * @param context Context to get resources and device specific display metrics

     * @return A float value to represent dp equivalent to px value

     */

    public static float convertPixelsToDp(float px, Context context){

        Resources resources = context.getResources();

        DisplayMetrics metrics = resources.getDisplayMetrics();

        float dp = px / (metrics.densityDpi / 160f);

        return dp;

    }


출처 : http://stackoverflow.com/questions/4605527/converting-pixels-to-dp



신고

submit

티스토리 툴바