Marc Van Daele
Marc Van Daele

Reputation: 2734

In Qt/QML, how to load different images for different device densities (Android)

I'm using Qt 5.4 and Qt Creator 3.3.2.

Loading different images, depending on the current OS, can be done with

Image {source: "logo.png"   }

and the following resources

logo.png
+windows/logo.png
+android/logo.png
+ios/logo.png

If I understand the documentation correctly, adding

+ios/logo.png
+ios/[email protected]
+ios/[email protected]

will, on iOS, select different images based on the device density.

Can I use a similar mechanism to load different images for different Android dpi's (ldpi, mdpi, hdpi, xhdpi, ...). If so, how should the directory structure look like?

Upvotes: 4

Views: 1388

Answers (2)

Nejat
Nejat

Reputation: 32665

You can calculate ppi using Screen.pixelDensity QML property and assign different images for different ranges of ppi. A sample code could be found in this KDAB blog post :

property int ppi: Screen.pixelDensity*25.4 

property var dir: ["MDPI","HDPI","XHDPI","XXHDPI",
                                    "XXXHDPI","XXXXHDPI"]
readonly property int ppiRange:{ 
 if (ppi>=540)
  5
 else if (ppi>=360)
  4
 else if (ppi>=270)
  3
 else if (ppi>=180)
  2
 else if (ppi>=135)
  1
 else
  0
 }

BorderImage {
   id: scalableElement3
   source: "./Images/" + dir[ppiRange] + "/image.png"
   width: parent.width-ppi/2
   height: ppi*1.5
   anchors.centerIn: parent
   border.left: 0.3*ppi; border.top: 0.3*ppi
   border.right: 0.18*ppi; border.bottom: 0.18*ppi
 }

Upvotes: 1

dtech
dtech

Reputation: 49319

Image {source: "logo" + density + ".png" }

And density can for example be S, M, L and you have logoS.png, logoM.png and logoL.png. Or you can use it to specify different path rather than image name. Either way.

You can use QScreen's logicalDotsPerInch property and expose that to QML to determine the value for density.

Also, if images are sufficiently big, you can actually get away with only shipping the larger version and scaling it down as needed. It will be easier and you will not be limited to particular sizes.

Upvotes: 4

Related Questions