Finding size of images imported at runtime

天大地大妈咪最大 提交于 2019-12-11 13:26:31

问题


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:


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.



来源:https://stackoverflow.com/questions/35333910/finding-size-of-images-imported-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!