Question

I am trying to create a simple android app in Java but I have hit a bump in the road.

I have an Array List that contains many Bitmaps and I am drawing them to the canvas but I am using the measurement of pixels and that doesn't come out right on most devices.

So is there any way to find out the size of my Graphic in dp and scale it to the screen density/size with dp and position it with dp or dip.

My Graphics ( Squares ) :

Graphic size in ldpi = 50px

Graphic size in mdpi = 75px

Graphic size in hdpi = 100px

Everyting else in the code is fine apart from it comes out looking weird?

Any help would be appreciated.

James.

Was it helpful?

Solution

From the android developer doc:

A virtual pixel unit that you should use when defining UI layout, to express layout dimensions or position in a density-independent way. The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a "medium" density screen. At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities

see this for more info.

OTHER TIPS

/**
 * Convert dp in pixels
 * @param dp
 * @return
 */
public int getPx(int dp){       
    float scale = getResources().getDisplayMetrics().density;
    return((int) (dp * scale + 0.5f));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top