dp-px-conversion

DpToPixels and PixelsToDp for Xamarin Android…

We all know the sea of Android devices consists of different kinds of Screen Densities, this is why in Android programming we always refer to Density Pixels instead of actual Pixels, so that we could use the exact value of Pixels that best catered for the given Screen Density of the  physical device.

Now this is going to be another flash post, where I share stuff in sweet and short form without any spoon feeding! 😛

Straight on Point:

(px) Pixels –

corresponds to actual pixels on the screen.

(dp or dip) Density-independent Pixels –

an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both “dip” and “dp”, though “dp” is more consistent with “sp”.

Extracted from: Android Developer Documentation

Well now when it comes to Xamarin Android development this is the same scenario, but the way we actually use it code could be a bit tricky.

So here I’m sharing the two Helper methods I came up with for the conversion inbetween actual Pixels and Device Independ Pixels value and Device Independ Pixels to actual Pixels value… 😀

/// <summary>
/// Device Independent Pixels to Actual Pixles conversion
/// </summary>
/// <param name="context"></param>
/// <param name="valueInDp"></param>
/// <returns></returns>
public static float DpToPixels(Context context, float valueInDp)
{
	DisplayMetrics metrics = context.Resources.DisplayMetrics;
	return TypedValue.ApplyDimension(ComplexUnitType.Dip, valueInDp, metrics);
}

/// <summary>
/// Actual Pixels to Device Independent Pixels conversion
/// </summary>
/// <param name="context"></param>
/// <param name="pixelValue"></param>
/// <returns></returns>
public static int PixelsToDp(Context context, float pixelValue)
{
	var dp = (int)((pixelValue) / context.Resources.DisplayMetrics.Density);
	return dp;
}

 

There you have it!

Enjoy! 😀

Advertisements

2 thoughts on “DpToPixels and PixelsToDp for Xamarin Android…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s