82 lines
2.3 KiB
C#
82 lines
2.3 KiB
C#
using System.Collections;
|
|
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
public class UIBGImageChange : MonoBehaviour
|
|
{
|
|
public bool _AutoFitSize;
|
|
public string _ResPath;
|
|
|
|
private void OnEnable()
|
|
{
|
|
InitImg();
|
|
}
|
|
|
|
protected virtual void InitImg()
|
|
{
|
|
ChangeRes(_ResPath);
|
|
}
|
|
|
|
protected void ChangeRes(string imgPath)
|
|
{
|
|
var rawImage = GetComponent<RawImage>();
|
|
if (rawImage != null)
|
|
{
|
|
rawImage.enabled = false;
|
|
StartCoroutine(SetTexture(rawImage, imgPath));
|
|
}
|
|
|
|
var image = GetComponent<Image>();
|
|
if (image != null)
|
|
{
|
|
image.enabled = false;
|
|
StartCoroutine(SetTexture(image, imgPath));
|
|
}
|
|
}
|
|
|
|
private IEnumerator SetTexture(RawImage rawImage, string path)
|
|
{
|
|
var filePath = Application.streamingAssetsPath + "/" + path;
|
|
#if UNITY_IPHONE || UNITY_IOS
|
|
filePath = "file://" + filePath;
|
|
#endif
|
|
//Debug.LogError("LoadLocalImage:" + filePath);
|
|
var www = new WWW(filePath);
|
|
yield return www;
|
|
if (!string.IsNullOrEmpty(www.error))
|
|
{
|
|
Debug.LogError("LoadImageError: " + www.error + "\n" + path);
|
|
rawImage.enabled = false;
|
|
}
|
|
else
|
|
{
|
|
rawImage.enabled = true;
|
|
var texture = www.texture;
|
|
rawImage.texture = texture;
|
|
if (_AutoFitSize)
|
|
rawImage.rectTransform.sizeDelta = new Vector2(texture.width, texture.height);
|
|
}
|
|
}
|
|
|
|
private IEnumerator SetTexture(Image image, string path)
|
|
{
|
|
var filePath = Application.streamingAssetsPath + "/" + path;
|
|
#if UNITY_IPHONE || UNITY_IOS
|
|
filePath = "file://" + filePath;
|
|
#endif
|
|
var www = new WWW(filePath);
|
|
yield return www;
|
|
if (!string.IsNullOrEmpty(www.error))
|
|
{
|
|
Debug.LogError("LoadImageError: " + www.error + "\n" + path);
|
|
image.enabled = false;
|
|
}
|
|
else
|
|
{
|
|
image.enabled = true;
|
|
image.sprite = Sprite.Create(www.texture, new Rect(0, 0, www.texture.width, www.texture.height),
|
|
new Vector2(0.5f, 0.5f));
|
|
if (_AutoFitSize) image.rectTransform.sizeDelta = new Vector2(www.texture.width, www.texture.height);
|
|
}
|
|
}
|
|
} |