微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使图片长宽与屏幕适配,尺寸更大/c# unity

如何解决使图片长宽与屏幕适配,尺寸更大/c# unity

我有一个下载图片的脚本 我希望图像的高度和宽度与屏幕匹配

图片 [1]:https://i.stack.imgur.com/0VcAT.png

图像应该以最佳方式呈现给用户 顺便说一句,这是一个看漫画的应用程序

" 我非常努力地以最好的方式传达这个想法,我希望我成功^_^ "

感谢您的帮助

脚本

public IEnumerator Getimage(string url)
{
    UnityWebRequest www = UnityWebRequestTexture.GetTexture(url);
    yield return www.SendWebRequest();

    Texture2D myTexture = DownloadHandlerTexture.GetContent(www);


    //خوارزمية تعديل حجم الصورة 
    // Give all 100 of the length or width one number
   for(int i = 1; i < 40;)
   {
       if(i*100 > myTexture.width)
       {
           for(int u = 1; u < 40;)
           {
              if(u*100 > myTexture.height)
              {
                WidthX = i;
                HeightX = u;
                u = 100;
                i = 100;
              } 
               u++;
           }
       }
       i++;
   }

    // After reducing all 100 to one,scale it down to fit the screen
    WidthX = WidthX / 3;
    HeightX = HeightX / 3;

    //Create sprite and set a Width and Height
    Rect rec = new Rect(0,myTexture.width,myTexture.height);
    OImg.sprite = Sprite.Create(myTexture,rec,Vector2.zero);
    OImg.GetComponent<RectTransform>().localScale = new Vector3 (WidthX,HeightX,1);        
    

}

我通过(localScale)改变了图像的大小,我认为这是一个错误

必须修改图像的“矩形变换宽度和高度”

解决方法

当您使用 RecTransformlocalScale 时,您使用的是 RawImageImage 来显示此纹理。不要尝试调整它的大小,只需使用 anchors

当它们出现在带有一些箭头的小框中的检查器中时,更容易在那里形成它们。您是否希望此图像不占据全屏?如果您希望它始终占据全屏,我可以为此添加一个解决方案,但这里有一个代码解决方案,它将强制您的 ImageRawImage 占据全屏,而不管给出的图像。

[SerializeField] private Transform CanvasTransform = null;

private RectTransform OImgRect = null;

private void Start()
{
    OImgRect = OImg.GetComponent<RectTransform>();
}

public IEnumerator GetImage(string url)
{
    ...   
    
    // set your image 
    OImg.sprite = Sprite.Create(myTexture,rec,Vector2.zero);
    
    // set our parent to the canvas while storing our previous parent
    Transform prevParent = transform.parent;
    
    // set the new parent to the canvas
    transform.SetParent(CanvasTransform,false);
    
    // fit it to screen
    FitToImageToScreen();
    
    // now set it back but using the true parameter to keep our scaling
    transform.SetParent(prevParent,true);
}

private void FitToImageToScreen()
{
    OImgRect.anchorMin = new Vector2(0,0);
    OImgRect.anchorMax = new Vector2(1,1);
    OImgRect.pivot = new Vector2(0.5f,0.5f);   
}

删除您试图使其适合屏幕的所有其他代码。只需使用锚点。如果您想要有关我使用的字段的来源,有 anchorMinanchorMaxpivot。它们是规范化值 [-1,1],描述了图像如何适合其父容器。只要您的 Canvas 组件适合您的屏幕并且 ImageRawImageOIImg 是它的直接子代,图像就会扩展到 Canvas .

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。