1
votes

I am currently loading images at runtime from directories stored in an XML file, and assigning them to RawImage components via the WWW class. While this is working fine, the image is skewed to fit into the new texture size.

I am wondering how to get an image’s original size or aspect ratio so that I can change the size of the image rect to suit. The images to be imported are at varying sizes and therefore the approach used needs to be responsive to the original size of imported images.

Any suggestions would be much appreciated. [Scripting in uJS]

Many thanks in advance, Ryan

function loadContextImage(texLocation : String)
{
    if (!imageView.activeSelf)
    {
        imageView.SetActive(true);
    }

    var wwwDirectory = "file://" + texLocation; //this will probably need to change for other OS (PC = file:/ [I think?]) - **REVISE**  
    var newImgTex = new Texture2D(512, 512);

    while(true){

        var www : WWW = new WWW(wwwDirectory);

        yield www;

        www.LoadImageIntoTexture(newImgTex);

        if (www.isDone){
            break; //if done downloading image break loop
        }
    }

    var imageRender : UI.RawImage = imageView.GetComponent.<RawImage>();
    imageRender.texture = newImgTex;
}
1
Can you use the preserve aspect ratio toggle?Everts
Do NOT use "unityscript", it is deprecated. Change to c#.Fattie
@fafase there doesn't seem to be method in the RawImage class for preserving aspect ratio; is there another method you are referring to?Ryan Achten
@Joe Blow thanks for the tip; I'm pretty invested in using uJS at this stage but will definitely be using c# in future projects. The duplicate link you have included seems to refer to the use of bounds to acquire dimension sizes. I don't think this suits my use case as the image is imported at runtime and I need to find dimensions of the image itself before assigning it to a renderer.texture, to ensure the texture is set to an appropriate size and avoid the aforementioned incorrect aspect ratio.Ryan Achten

1 Answers

0
votes

If you cannot use an Image (for nay valid reasons), you can get the width and height of the texture:

WWW www = new WWW(url);
yield return www;
Texture2D tex = www.texture; 
float aspectRatio = tex.height / tex.width;
rawImage.width = width;
rawImage.height = width * aspectRatio;

This should make the rect of the image of the appropriate ratio of the texture.

If you can use Image and preserveAspectRatio, you get it done by Unity. The result is not necessarily the same since it will keep the dimensions of the box and make the Sprite occupies as much space while keeping ratio.