Home / Article / Materials and Textures: Scale to Fit and Crop

Materials and Textures: Scale to Fit and Crop

/
/
/
251 Views

Hey! long time, no see 🙂

This week, I want to share with you a small script to adjust the scaling and offset of a material’s texture. You can use it to apply different scaling modes – Scale to Fit or Crop – and use it in the editor or at runtime.

Materials and Textures

By default, a texture stretches with the mesh size (in this case, I’m using a Quad).

Materials and Textures: Scale to Fit and Crop
Stretch

I was having this problem when trying to apply different images to a television and computer screen (both 3d meshes). These, are uploaded by users and I don’t have any control over their size and ratio. So, I’ve decided to implement this script – MaterialScaleModifier – to adjust the texture scale to the mesh size.

The full script is available at the bottom of the page (and soon on github).

How to use it

  • Apply the MaterialScaleModifier.cs to the mesh; IMAGE1
  • Editor: Choose the Scaling Mode;
  • Runtime: Reference the component and call the ScaleTexture() method; IMAGE2 
Materials and Textures: Scale to Fit and Crop
Scale to Fit
Materials and Textures: Scale to Fit and Crop
Crop

The Scale to Fit does not work with all textures!

When scaling the image, the border pixels are repeated to fill the remaining space. In this way, the Scale to Fit only works with images with a homogeneous background (e.g. solid colour) and no details touching the image border.

Materials and Textures: Scale to Fit and Crop
Scale to Fit

To solve this problem, I’m adding a small black border around all images before downloading them into Unity. Not perfect but good enough for my case.

This does not happen when cropping the image

Happy Coding 🙂

MaterialScaleModifier.cs

Download Script  
  • Facebook
  • Twitter
  • Google+
  • Linkedin
  • Pinterest
  • Reddit

Leave a Comment

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