Cocos2dx Device::getDpi() confusion on android


#1

I am trying to get the device ppi but it looks like on android it’s wrong.

I tried a nexus 4 which has 318 ppi but when I do getDpi it returns 320.
I tried Samsung galaxy s7 and it returned 640 but it’s suppose to be 577.

It seems to work fine on ios…

Also I think it’s miss leading that it’s called getDpi for actually getting the ppi?


#2

Can you tell me why you are doing this? In 4 years, I haven’t used this once, nor come across anyone that has.


#3

To get the diagonal screen size in inches


#4

Does getting the height and width not work for your needs?


#5

Can you get the width and height in inches? If so that would be enough. But even so I think getDpi should work. Maybe even renamed Ppi if that was the original intension. I see a few topics about this but it always seems to get forgotten about.

But I don’t think they realize also that it’s not accurate for android


#6

I can check to see what getDpi() is doing and what it should do.

Edit: issue created: https://github.com/cocos2d/cocos2d-x/issues/18463


#7

Thank you! :smiley:


#8

@ericb365, I checked the getDPI interface, and it returns correct on different devices.
DPI means Dots per inch, PPI means Pixels per inch.
Currently, Device::getDPI is returning correct result.
Do you wanna a new API for getting PPI ?


#9

Yes a ppi api would be nice


#10

Before we add a new interface called Device::getPPI, you could make one by yourself using following code:

        DisplayMetrics dm = new DisplayMetrics();
        Display d = getWindowManager().getDefaultDisplay();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            d.getRealMetrics(dm);
        } else {
            d.getMetrics(dm);
        }

        double x = Math.pow(dm.widthPixels / dm.xdpi, 2);
        double y = Math.pow(dm.heightPixels / dm.ydpi, 2);

        double screenInches = Math.sqrt(x + y);
        Log.d("cjh", "Screen inches : " + screenInches);
        double ppi = Math.sqrt(dm.widthPixels * dm.widthPixels + dm.heightPixels * dm.heightPixels) / screenInches;
        Log.d("cjh", "dpi: " + dm.densityDpi + ", ppi: " + ppi);

#11

Okay nice this works! It’s a little bit off but good enough for what I need it for. So with @dumganhar code, a Samsung galaxy s7 returns 576.6554669457003 ppi and a nexus 4 returns ppi of 319.0206090553892.

The s7 is suppose to be 577 but we can round that.
The nexus 4 is suppose to be 318 but it’s not a huge deal.

Thanks @dumganhar :slight_smile: