0

Xamarin forms controls having the margin, padding, width and height property, how to convert this property values to pixel.

Already got some the reference link for converting db to px, but default xamarin form is px or db is the doubt?

public float convertDpToPx(Context context, float dp) 
{
  return dp * context.getResources().getDisplayMetrics().density; 
}

Converting pixels to dp

And is it possible convert the width and height value to pixel in xamarin(uwp, Android and iOS)?

Thanks in advance.

Nico Zhu
  • 32,367
  • 2
  • 15
  • 36
  • Check out https://learn.microsoft.com/en-us/xamarin/xamarin-forms/creating-mobile-apps-xamarin-forms/summaries/chapter05 – Nongthonbam Tonthoi Sep 05 '20 at 02:50
  • Your question seems same as this: https://stackoverflow.com/questions/63612367/convert-xamarin-forms-measure-units-to-pixels/63615455#63615455 –  Sep 05 '20 at 07:53
  • @deirahi, thanks, i go through that link, some clarification need, I'm beginner in android could please explain me why we need to convert db to px? – Saravanakumar Natarajan Sep 06 '20 at 18:52
  • I have not so much experience too. So, I don't know why, but I guess some API and library need pixel. –  Sep 07 '20 at 00:43

1 Answers1

0

dp is Density-Independent-Pixels, dp is commonly used in Android development to adapt to mobile phones. Google stipulates that when there are 160 pixels (px) on a 1-inch screen, then 1dp=1px=1dpi.

The purpose of android dp is adaptive mobile phones different sizes and resolutions, a dp value allows the Android system to automatically select the matched resources. in other words the dp value can be obtained through a certain way to obtain the corresponding image resource or size according to the equipment requirements.

And xamarin has provide Xamarin.Essentials that use to get current monitor's Density. And the you could use the relationship of dp and px to get dp from px.(the default unit of xamrin width and height is px)

public static int px2dip(DisplayInfo mainDisplayInfo, float pxValue)
{
    float scale = (float)mainDisplayInfo.Density;
    return (int)(pxValue / scale + 0.5f);
}

var dp = px2dip(DeviceDisplay.MainDisplayInfo, pxvalue);
CoCaIceDew
  • 228
  • 1
  • 7