Time for action – scaling UI images according to pixel density

Follow these steps to scale the UI images of your app with a few lines of JavaScript:

  1. Define a CSS class to mark all the images you want to handle according to the device pixel ratio.
    <img class='highRes' />
  2. Create a script able to get all the images marked with the previously defined class and change their width according to the pixel ratio.
    function processImages(){
    
      var pixelRatio = window.devicePixelRatio;
      if(window.devicePixelRatio > 1) {
        var matches = document.querySelectorAll("img.highRes");
        for(var i = 0; i < matches.length; i++) {
          
          matches[i].width = (matches[i].width / pixelRatio);
        
        }
    }
  3. Run the script when the page is loaded or when the deviceready event is fired. When using PhoneGap, it is strongly recommended that the code that needs to run at startup is executed immediately after the deviceready event.
    addEventListener('deviceready', onDeviceReady);
    
    function onDeviceReady(evt){
    
      processImages();
    
    }

What just happened?

The images that compose the UI of the app are adapting themselves to the device pixel ratio with a really simple and fast script. In this way, the look and feel of the app will be consistent with the design provided to you.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.40.207