Scale to Fit and Crop a Quad Texture
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). So, if the provided image does not match the mesh ratio, it will become distorted.
I was having this problem when trying to apply different images to a television and computer screen (both 3d meshes). These, are images uploaded by users and I don’t have any control over their size and ratio. So, I’ve decided to implement this script – MaterialScaleModifier.cs – to adjust the texture scale to the mesh size.
How to use it
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.
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.
Happy Coding 🙂