Loading Images Based on DPI
An application developed based on the JS UI framework may be applied to different devices. Due to different DPIs of devices, different image resources may need to be configured. This framework allows devices with different DPIs to load different image resources. You only need to perform Defining Resource Files and Referencing Resources to use this function.
Defining Resource Files
In the /resources directory described in File Organization, you can define resource files for devices with different DPIs. JSON files are used to save resource definitions in the framework. For example, the resource file res-ldpi.json applies to a low-density (ldpi) screen (-120 dpi), and the resource file res-xxhdpi.json applies to an ultra-high-density (xxhdpi) screen (-480 dpi).
The reference density is 160 dpi, and the low density is 0.75 x 160 dpi. For details, see Table 1.
Table 1 Configuration qualifiers for different pixel densities
Extra extra extra high-density screen (~640 dpi) (4.0 x 160 dpi) |
The format of the resource file content is as follows:
{
"image": {
"wearable": "common/wearable.png",
"computer": "image/computer.jpg"
}
}
Referencing Resources
You can use the $r syntax in .hml and .js files to format image resources and obtain different image resources for different DPI devices.
Table 2 Resource formatting
Replaces the resource path based on the DPI of the current device: this.$r('image.wearable') |
NOTE: If the DPI of the device does not completely match any DPI defined in Table 1, a resource file closer to the DPI of the device is selected. For example, if the current device density is 2.7 x 160 dpi, resources defined in res-xxhdpi.json are selected. You can define a res-defaults.json file that will be selected by your application if required resource strings do not exist in res-xxhdpi.json. If the required resource strings are still not found in res-defaults.json, the image fails to be loaded.
-
Sample code for resource formatting
<!-- xxx.hml --> <div> <!-- Use $r to set the path of the image resource in the JSON file. --> <image src="{{ $r('image.wearable') }}" class="image"></image> <image src="{{ computer }}" class="image"></image> </div>
// xxx.js // The following example shows how to use $r in a .js file. export default { private: { computer: '', }, onInit() { // Format resources. this.computer = this.$r('image.computer'); }, }