Responsive images in Sitecore

Posted 01/31/2014 by Justin Pettinger

Responsive design is now a major design element for almost every new website being created right now. With responsive design the expectation are responsive and scale based on the browser dimensions.
This is a issue in Sitecore if you use the Sitecore image webcontrol due to the fact the image tag auto populates the height and width. Below is a example html markup generated by the Image webcontrol.

<img src="~/media/hero-home-1.png" alt="Homepage hero" width="1319" height="720" />

Image webcontrol

public class Image : Sitecore.Web.UI.WebControls.Image
{
   public bool IsResponsive { get; set; }

   protected override void PopulateParameters(SafeDictionary parameters)
   {
      base.PopulateParameters(parameters);
      parameters.Add("isResponsive", IsResponsive ? "1" : "0");
   }
}
The above code add a IsResposonisve property to the Image control and pass the data to renderField pipeline.

Next week create the ResponsiveImageRenderer class. This class will be responsible to disable the output of the width and height if IsResponsive property is set to true.
public class ResponsiveImageRenderer : Sitecore.Xml.Xsl.ImageRenderer
{
   protected override System.Drawing.Size GetFinalImageSize(Size imageSize, Size size, Size maxSize)
   {
      Size finalImageSize = base.GetFinalImageSize(imageSize, size, maxSize);

      if (this.Parameters["isResponsive"] == "1")
      {
         finalImageSize.Width = 0;
         finalImageSize.Height = 0;
      }

      return finalImageSize;
   }
}
The above class implements the ImageRenderer and override the GetFinalImageSize function. The class checks to see if the IsResponsive set to true. If it is then the width and height is set to 0. The width and height are not output to the page if they are set to 0.

The next step is to create another class called GetResponsiveImageFieldValue. This class is responsible to update the pipeline to call the ResponsiveImageRenderer in the pipeline.

public class GetResponsiveImageFieldValue : GetImageFieldValue
{
   protected override Sitecore.Xml.Xsl.ImageRenderer CreateRenderer()
   {
      return new ResponsiveImageRenderer();
   }
}
The above class override the CreateRenderer control to return the ResponsiveImageRenderer().

Finally we need to update the config to allow the GetResponsiveImageFieldValue to be called instead of GetImageFieldValue.

   


to

   


Make sure to update ResponsiveImages.BL.GetResponsiveImageFieldValue, ResponsiveImage to the correct name space and assembly name.

Share:

Archive

Syndication