Home / Article / Scale to Fit and Crop a Quad Texture

Scale to Fit and Crop a Quad Texture

/
/
/
361 Views

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.

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 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

  • 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.

This does not happen when cropping the image

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.

I’m currently using ImageMagick to apply the black border around each image. It runs in all platforms and it’s very simple to apply this effect to multiple images with a single command line.

You should use a border with at least 8 px

Happy Coding 🙂

MaterialScaleModifier.cs

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

Talk to me :)
%d bloggers like this: