convert Dimension from pixel To Dimension Strictly - Android Graphics

Android examples for Graphics:Pixel

Description

convert Dimension from pixel To Dimension Strictly

Demo Code


//package com.java2s;

import android.content.Context;

import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;

public class Main {
    private static final String TAG = "ViewUtils";

    public static float convertDimension(int unitFrom, int unitTo,
            float value, Context context) {
        if (context == null) {
            Log.w(TAG,//from  w  ww.j  av a  2s  .  c  om
                    "Argument 'context' is null at convertDimension(int, int, float, Context)");
            return 0;
        }
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();

        float pixelValue = dimensionToPixelStrictly(unitFrom, value,
                metrics);
        return pixelToDimensionStrictly(unitTo, pixelValue, metrics);
    }

    private static float dimensionToPixelStrictly(int unit, float value,
            DisplayMetrics metrics) {
        switch (unit) {
        case TypedValue.COMPLEX_UNIT_PX:
            return value;
        case TypedValue.COMPLEX_UNIT_DIP:
            return value * metrics.density;
        case TypedValue.COMPLEX_UNIT_SP:
            return value * metrics.scaledDensity;
        case TypedValue.COMPLEX_UNIT_PT:
            return value * metrics.xdpi * (1.0f / 72);
        case TypedValue.COMPLEX_UNIT_IN:
            return value * metrics.xdpi;
        case TypedValue.COMPLEX_UNIT_MM:
            return value * metrics.xdpi * (1.0f / 25.4f);
        }
        return 0;
    }

    private static float pixelToDimensionStrictly(int unit, float value,
            DisplayMetrics metrics) {
        switch (unit) {
        case TypedValue.COMPLEX_UNIT_PX:
            return value;
        case TypedValue.COMPLEX_UNIT_DIP:
            return value / metrics.density;
        case TypedValue.COMPLEX_UNIT_SP:
            return value / metrics.scaledDensity;
        case TypedValue.COMPLEX_UNIT_PT:
            return value / (metrics.xdpi * (1.0f / 72));
        case TypedValue.COMPLEX_UNIT_IN:
            return value / metrics.xdpi;
        case TypedValue.COMPLEX_UNIT_MM:
            return value / (metrics.xdpi * (1.0f / 25.4f));
        }
        return 0;
    }
}

Related Tutorials