How to convert dp to px in xamarin.android?
<p>I want to convert dp to px in my <strong>C# code</strong> in <strong>xamarin.android</strong>, but all I could find were <strong>java codes</strong> in android studio that <strong>have some problems in xamarin</strong>. I tried to use equivalent like using Resources instead of getResources() and I could solve some little problems, but there are some problems yet that I couldn't find any equivalent for them. here are original codes, my codes, and my codes problems in xamarin:</p>
<h2>First code</h2>
<p>(found from <a href="https://stackoverflow.com/questions/5959870/programatically-set-height-on-layoutparams-as-density-independent-pixels">Programatically set height on LayoutParams as density-independent pixels</a>)</p>
<p><strong>java code</strong></p>
<pre><code>int height = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, &lt; HEIGHT &gt;, getResources().getDisplayMetrics());
</code></pre>
<p><strong>C# code</strong></p>
<pre><code>int height = (int)TypedValue.ApplyDimension(TypedValue.COMPLEX_UNIT_DIP, &lt; HEIGHT &gt;, Resources.DisplayMetrics);
</code></pre>
<p><strong>problems:</strong></p>
<ul>
<li><p>'TypedValue' does not contain a definition for 'COMPLEX_UNIT_DIP'</p>
</li>
<li><p>Invalid expression term &lt; (The same error for &gt;)</p>
</li>
<li><p>The name 'HEIGHT' does not exist in the current context</p>
</li>
</ul>
<h2>Second code</h2>
<p>(found from <a href="https://stackoverflow.com/questions/8309354/formula-px-to-dp-dp-to-px-android">Formula px to dp, dp to px android</a>)</p>
<p><strong>java code</strong></p>
<pre><code>DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
</code></pre>
<p><strong>C# code</strong></p>
<pre><code>DisplayMetrics displayMetrics = Application.Context.Resources.DisplayMetrics;
int pixel = Math.Round(dp * (displayMetrics.Xdpi / DisplayMetrics.DensityDefault));
</code></pre>
<p><strong>problem</strong></p>
<ul>
<li>Operator '/' cannot be applied to operands of type 'float' and 'DisplayMetricsDensity'</li>
</ul>
<p>Now I have actually two questions. Which code is more proper? What's equivalent code for them in xamarin.android?</p>
<p>Thanks in advance.</p>