How to convert dp to px in xamarin.android?

Solution to "First code":

Xamarin tends to move constants into their own enums. COMPLEX_UNIT_DIP can be found on ComplexUnitType enum. Also you cannot have < HEIGHT > in your code you actually need to pass in dips to get the equivalent pixel value. in the example below I am getting pixels in 100 dips.

var dp = 100;
int pixel = (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, dp, Context.Resources.DisplayMetrics);

Solution to "Second code":

You need to explicitly cast 'DisplayMetrics.DensityDefault' to a float and the entire round to an int:

int pixel = (int)System.Math.Round(dp * (displayMetrics.Xdpi / (float)DisplayMetrics.DensityDefault));

I prefer the first approach as the second code is specifically for calculating along the "x dimension": Per Android docs and Xamarin.Android docs, the Xdpi property is

"The exact physical pixels per inch of the screen in the X dimension."


These are from the project that I am currently working on..

public static float pxFromDp(Context context, float dp)
{
    return dp * context.Resources.DisplayMetrics.Density;
}

public static float dpFromPx(Context context, float px)
{
    return px / context.Resources.DisplayMetrics.Density;
}