UIWebView and iPhone 4 retina display

前端 未结 6 1833
予麋鹿
予麋鹿 2020-12-13 07:48

I have a UIWebView which displays some local text and images. Either I\'ve made a mistake somewhere, or the UIWebView doesn\'t automatically handle

6条回答
  •  难免孤独
    2020-12-13 08:17

    I use this Javascript hack to load scaled images when running on a retina device. It will change the src and width attribute on all images to use the corresponding scaled image. Note that I have only tested this with local images.

    Setting display: none and then reset it on image load seams to fix some flickering. Also note that this code is probably not compatible with other browsers than WebKit.

    document.addEventListener("DOMContentLoaded", function() {
      var scale = window.devicePixelRatio;
      // might want this to be scale != 2
      if (scale == undefined || scale == 1) {
        return;
      }
    
      var re = /^(.*)(\..*)$/;
      var images = document.getElementsByTagName("img");
      for (var i =  0; i < images.length; i++) {
        var img = images[i];
        var groups = re.exec(img.src);
        if (groups == null) {
          continue;
        }
    
        img.style.setProperty("display", "none");
        img.addEventListener("load", function(event) {
          event.target.width /= scale;
          event.target.style.setProperty("display", "");
        });
        img.src = groups[1] + "@" + scale + "x" + groups[2];
      }
    });
    

    Tips is to add this to a file called e.g. scaledimages.js and then use

    
    

    Make sure the js-file is listed in "Copy Bundle Resources" and not in "Compiled Sources" in your targets "Build phases". Default Xcode seams detect Javascript files as something it likes to compile. Also note that the current script might break things if devicePixelRatio happen to be 3 or greater in the future, a precaution might be to change the (scale == undefined || scale == 1) to scale != 2 only load @2x for now.

    Update: There is also a jQuery-Retina-Display-Plugin that does something similar but requires you to set the width attribute and seams to also use a HEAD request to see if the image exist, not sure how that will work for local files.

提交回复
热议问题