using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace JHL
{
public class TestJHL : MonoBehaviour
{
public RawImage rawImage;
//图片底版大小
public float _FloatShowImageBiLi = 0;
public float _FloatShowImageBiLiW = 0;
public float _FloatShowImageBiLiH = 0;
//加载图片大小
public float _FloatLoadingTextureBiLi = 0;
public float _FloatLoadingTextureBiLiW = 0;
public float _FloatLoadingTextureBiLiH = 0;
//测试数据
public List<string> StringPathForTexture;
public List<Button> _Button_Change;
private Texture2D _Texture2DLoadingTemp;
void Start()
{
InitializationTuPian();
}
#region 测试图片自动调整大小
void InitializationTuPian()
{
//获取容器大小
_FloatShowImageBiLiW = (float)rawImage.GetComponent<RectTransform>().rect.width;
_FloatShowImageBiLiH = (float)rawImage.GetComponent<RectTransform>().rect.height;
//计算图片宽高比
_FloatShowImageBiLi = _FloatShowImageBiLiW / _FloatShowImageBiLiH;
//注册按钮事件
for (int i = 0; i < _Button_Change.Count; i++)
{
int tempI = i;
_Button_Change[tempI].onClick.AddListener(() =>
{
StartCoroutine(LoadRawImg( StringPathForTexture[tempI]));
});
}
}
IEnumerator LoadRawImg(string path)
{
WWW www = new WWW("file://" + Application.streamingAssetsPath + "/" + path);
yield return www;
//调整图片大小,在进行赋值
_Texture2DLoadingTemp = new Texture2D(0, 0);
_Texture2DLoadingTemp = www.texture;
//使用原始图片和加载图片进行宽高比调整
_FloatLoadingTextureBiLi = (float)_Texture2DLoadingTemp.width / (float)_Texture2DLoadingTemp.height;
_FloatLoadingTextureBiLiW = _Texture2DLoadingTemp.width;
_FloatLoadingTextureBiLiH = _Texture2DLoadingTemp.height;
//设置宽和高
rawImage.GetComponent<RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, _Texture2DLoadingTemp.width);
rawImage.GetComponent<RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, _Texture2DLoadingTemp.height);
//根据大小设置比例
float tempSizeScale = 1;
if(_FloatShowImageBiLi>= _FloatLoadingTextureBiLi)
{
//根据宽度修改
tempSizeScale = _FloatShowImageBiLiH / _FloatLoadingTextureBiLiH;
}
else
{
//根据高度进行修改
tempSizeScale = _FloatShowImageBiLiW / _FloatLoadingTextureBiLiW;
}
rawImage.texture = _Texture2DLoadingTemp;
rawImage.GetComponent<RectTransform>().localScale = new Vector3(tempSizeScale, tempSizeScale, tempSizeScale);
}
#endregion
}//END CLASS
}
文章来源地址https://www.toymoban.com/news/detail-739080.html
文章来源:https://www.toymoban.com/news/detail-739080.html
到了这里,关于unity加载图片并自适应RawImage大小的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!