How to Make a Retina Sprite with LESS

1. add the following snippet to your LESS file:

.retina-sprite(@positionX,@positionY,@width,@height,@background1x,@background2x,@retinaImageWidth) {
  background-image: url(@background1x);
  background-position-x: @positionX/2px;
  background-position-y: @positionY/2px;
  background-repeat: no-repeat;
  width: @width/2px;
  height: @height/2px;

  @media (-webkit-min-device-pixel-ratio: 1.5), (min-resolution: 144dpi){
    background-size: @retinaImageWidth/2px;
    background-image: url(@background2x);
  }
}

2. make the sprite at http://spritepad.wearekiss.com/ using retina sized icons
– to avoid issues with the non-retina dimensions, make sure the width and height are both even numbers so they can be split in half with no remainder

3. Use photoshop or your preferred image editing software to make a non-retina copy of your retina sprite
for example, in photoshop:
– open the retina sprite image
– push cmd + option + I (or go to Image > Image Size)
– set the size of the image to half the current size
– save as a new file

4. Using the background position, width, and height from the css generated by spritepad, do the following for each icon element in your LESS file:

.my-icon {
    // .retina-sprite(background-position-x, background-position-y, width, height, '/path/to/non-retina.png', '/path/to/retina.png',retina-image-width);

    .retina-sprite(-51,0,100,51,'/src/main/image/myimage-1x.png','/src/main/images',544);
}

notice that you never use ‘px’ for any of the values

6. To simplify your work, create a helper for the above task. Since you’ll probably only have one sprite for the whole less file, you don’t need to keep defining the path to the images or the image width:

.my-retina-helper(@background-x,@background-y,@width,@height) {
    .retina-sprite(@background-x, @background-y, @width, @height, '/src/main/image/myimage-1x.png', '/src/main/images',544);
}

.my-icon {
    .my-retina-helper(-51,0,100,51);
}

Leave a Reply

Your email address will not be published. Required fields are marked *