Android Question Calculate number of pixels = 3cm

wonder

Expert
Licensed User
Longtime User
Good morning!

I know this is a beginners question (and I should be ashamed of myself) but how do I calculate the amount of (horizontal) pixels which corresponds to 3 centimeters.

(I want an image to be ~3cm wide, no matter which phone, tablet, toaster, screen or Android TV!)

Can anyone help me out with a formula and/or B4A code?

Many many thanks in advance!
 

udg

Expert
Licensed User
Longtime User
Hi,
in my dgBarCode lib I had the goal to precisely respect the dimensions set by symbology standards. So I made use of the following routines:
B4X:
'converts dots-per-inch into dots-per-millimeter
Private Sub dpi2dpmm(val As Float) As Float
  Return (val / 25.4)
End Sub 

'returns Display metrics in inches or millimeters
Private Sub getDisplayMetrics(Xaxis As Boolean, UnitInches As Boolean) As Float
  Dim xdpi, ydpi As Float
  Dim r As Reflector
  r.Target = r.GetContext
  r.Target = r.RunMethod("getResources")
  r.Target = r.RunMethod("getDisplayMetrics")
  xdpi=r.GetField("xdpi")  'is xdpi an int or a float?
  ydpi=r.GetField("ydpi")
   If Xaxis Then
    If UnitInches Then Return xdpi Else Return dpi2dpmm(xdpi)
   Else
    If UnitInches Then Return ydpi Else Return dpi2dpmm(ydpi)
   End If
End Sub

You use it like this:
w = 0.33 * getDisplayMetrics(True,False) 'width 0.33 mm

In my case it worked well. Try it.

udg
 
Upvote 0

padvou

Active Member
Licensed User
Longtime User
Hi,
in my dgBarCode lib I had the goal to precisely respect the dimensions set by symbology standards. So I made use of the following routines:
B4X:
'converts dots-per-inch into dots-per-millimeter
Private Sub dpi2dpmm(val As Float) As Float
  Return (val / 25.4)
End Sub

'returns Display metrics in inches or millimeters
Private Sub getDisplayMetrics(Xaxis As Boolean, UnitInches As Boolean) As Float
  Dim xdpi, ydpi As Float
  Dim r As Reflector
  r.Target = r.GetContext
  r.Target = r.RunMethod("getResources")
  r.Target = r.RunMethod("getDisplayMetrics")
  xdpi=r.GetField("xdpi")  'is xdpi an int or a float?
  ydpi=r.GetField("ydpi")
   If Xaxis Then
    If UnitInches Then Return xdpi Else Return dpi2dpmm(xdpi)
   Else
    If UnitInches Then Return ydpi Else Return dpi2dpmm(ydpi)
   End If
End Sub

You use it like this:
w = 0.33 * getDisplayMetrics(True,False) 'width 0.33 mm

In my case it worked well. Try it.

udg
Could you please explain a little about the true false clauses of the function?
Thank you.
 
Upvote 0

klaus

Expert
Licensed User
Longtime User
From the code:
If Xaxis = True returns the X axis value
If Xaxis = False returns the Y axis value
If UnitInches = True returns the dpi value (dpi dots per inch)
If UnitInches = False returns the number of dots per mm
 
Upvote 0
Top