Runtime Texture Scaling in Unity3d
Code: Scaling an image the way that Texture2D.Resize does not.
If you are creating images or altering them in real-time you may need to resize them at some point, so armed with Unity3d’s new GetPixelBilinear(float,float) function we can do a reasonable job of scaling an image at runtime. The function below “ScaleTexture” is written in c#, it takes 3 arguments and should be used as such:-
Returned Image(Texture 2d)= ScaleTexture(Source Image(Texture2D),Target Width(Int),Target Height(Int));
private Texture2D ScaleTexture(Texture2D source,int targetWidth,int targetHeight) {
Texture2D result=new Texture2D(targetWidth,targetHeight,source.format,true);
Color[] rpixels=result.GetPixels(0);
float incX=((float)1/source.width)*((float)source.width/targetWidth);
float incY=((float)1/source.height)*((float)source.height/targetHeight);
for(int px=0; px<rpixels.Length; px++) {
rpixels[px] = source.GetPixelBilinear(incX*((float)px%targetWidth),
incY*((float)Mathf.Floor(px/targetWidth)));
}
result.SetPixels(rpixels,0);
result.Apply();
return result;
}
Texture2D result=new Texture2D(targetWidth,targetHeight,source.format,true);
Color[] rpixels=result.GetPixels(0);
float incX=((float)1/source.width)*((float)source.width/targetWidth);
float incY=((float)1/source.height)*((float)source.height/targetHeight);
for(int px=0; px<rpixels.Length; px++) {
rpixels[px] = source.GetPixelBilinear(incX*((float)px%targetWidth),
incY*((float)Mathf.Floor(px/targetWidth)));
}
result.SetPixels(rpixels,0);
result.Apply();
return result;
}



6 Comments
Awsome man, worked very nice! Thanks for sharing!
A very nice little function, I shall make use of this. Thanks!
Yep. Worked like a charm. Thanks.
Superb. Thank you so much
(A/B) * (C/D) = (AC)/(BD). Now we have :
float incX=((float)1 / source.width) * ((float)source.width/targetWidth);
this is equal to float incX = (1.0 / (float)targetWidth);
right ?
great helper function tho. THX
Absolutely, you are quite correct! I guess at the time I was going for the result, and my simple brain didn’t even think that through properly, always good to get clarity and optimisations, thank you.