Can Android support dp's less than 1dp?

后端 未结 3 1945
予麋鹿
予麋鹿 2020-12-23 11:24

I am making a calendar and I need a grid. Problem is the borders, or rather the space between each grid, which is what I am using to kind of simulate a grid, is 1 dp. But it

相关标签:
3条回答
  • 2020-12-23 12:03

    Yes.

    I set to 0.1dp and it is smaller than 1dp on my 4" ME860 DRIOD.

    0 讨论(0)
  • 2020-12-23 12:14

    Android does allow you to enter fractional values for dp into XML, though I'm not sure I would recommend it because the results become less easy to predict/compute. Devices convert dp values into pixels using (basically) the following formula:

    px = (int)(scale * dp + 0.5)
    

    (i.e. the device density scale rounded to the nearest whole pixel value)

    The scale value would be based on the screen density of the device:

    • MDPI = 1
    • HDPI = 1.5
    • XHDPI = 2
    • XXHDPI = 3

    So 0.5dp would result in {1px, 1px, 1px, 2px} for the above densities, whereas 1dp would be {1px, 2px, 2px, 3px}. A tiny value like 0.1dp would resolve to {1px, 1px, 1px, 1px} because anything less than 1 in the above formula resolves to a single pixel unless the value was explicitly 0dp (it's not possible to draw something thinner than a single pixel width).

    If you want to ensure that thinnest possible width is used, probably best to define the width explicitly with px instead of a scaled unit like dp. Setting a value of 1px will draw with a single pixel on all devices, and is much more readable than hoping 0.5dp or 0.1dp does the same.

    0 讨论(0)
  • 2020-12-23 12:14

    Simple answer is yes, you can.

    Simpe solution to your problem (i.e. achieve the thinnest possible line) set thinckness to: 1px

    I suggest px as its not device dependant and it is the smallest measure available, furthermore it wont be converted into another form, therefore no rounding errors nor any unexpected rendering... let me explain.

    Android layout xml file, or dimensions xml values file, will allow you to enter decimal values for dp.

    HOWEVER: I have experimented with several values from 0.1dp to 1dp, on many devices. Depending on the device - it may not render so as you expect.

    On lower pixel density devices, the lines may render thicker on one side compared to another side even though they are coded to have the same... This is due to inaccuracy introduced when truncating the converted to dp to px value - (as Devunwired mentions):

    px = (int)(scale * dp + 0.5)
    

    A pixel (px) is the smallest unit and must be an integer. so - if your aim is to simply have the smallest possible line/border, why not set it to:

    1px

    I hope this helps!

    0 讨论(0)
提交回复
热议问题