简体   繁体   中英

Android - Can't draw same size square on all devices

I have an application running on android on which I have to draw a grid. I would like the cells of the grid to be of the same size on all devices, and I've found this method to do that:

float scale = getResources().getDisplayMetrics().density;
float SIZE =  DESIRED_DP_VALUE * scale + 0.5f;

DESIRED_DP_VALUE is a value I set for the cells dimension.
I've tried the app on two smartphones and a tablet: the tablet and one of the smartphones have the cells of the same size, while the other smartphone doesn't.

This is the method I use to draw the grid:

protected void onDraw(Canvas canvas) {
    canvas.drawColor(Color.BLACK);
    int count=0;

    while(count<=row){
        float coordinate=count*SIZE;
        canvas.drawLine(coordinate,0,coordinate,column*SIZE,whitePaint);
        count++;
    }

    count=0;

    while(count<=column){
        float coordinate=count*SIZE;
        canvas.drawLine(0,coordinate,row*SIZE,coordinate,whitePaint);
        count++;
    } 
}

The grid is draw correctly on each device. Where could the problem be?

I think you are mixing some concepts. The size in pixels is that, how many dots are counting per with or height. Every device has its own screen size measured in inches and the amount of pixels or dots able to draw in width and height. The relationship between dimension and pixels is the density. So, what do you want to do? Draw an square which shows the same physical size on the screen or a square with the same amount of pixels? If you want to draw based on inches, take it that way. For drawing an one inch square, for a device with a density of 300 pixels per inch you need 300 pixels. If the device is 150 pixels per inch, you must draw a 150 pixels square. So, you need to keep fixed the size in inches, not the desired DP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM