Search code examples
imageunity-game-engineruntimeunityscriptdimensions

Finding size of images imported at runtime


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

Solution

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