62 lines
1.8 KiB
C#
62 lines
1.8 KiB
C#
using System.Collections;
|
|
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
public class UiBgLoaderV2 : MonoBehaviour
|
|
{
|
|
public string texturePath;
|
|
|
|
private void OnTextureLoad(Texture2D texture)
|
|
{
|
|
var rawImage = GetComponent<RawImage>();
|
|
var image = GetComponent<Image>();
|
|
if (rawImage)
|
|
{
|
|
if (texture)
|
|
{
|
|
rawImage.enabled = true;
|
|
rawImage.texture = texture;
|
|
}
|
|
else
|
|
rawImage.enabled = false;
|
|
}
|
|
if (image)
|
|
{
|
|
if (texture)
|
|
{
|
|
image.enabled = true;
|
|
image.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.one * 0.5f);
|
|
}
|
|
else
|
|
image.enabled = false;
|
|
}
|
|
if (texture)
|
|
{
|
|
var rectTransform = (RectTransform)transform;
|
|
var canvasRoot = (RectTransform)rectTransform.root;
|
|
var screenSize = canvasRoot.sizeDelta;
|
|
var ratio = Mathf.Max(screenSize.x / texture.width, screenSize.y / texture.height);
|
|
rectTransform.sizeDelta = new Vector2(texture.width, texture.height) * ratio;
|
|
}
|
|
else
|
|
Debug.LogError("Failed to Load Texture for Bg: " + texturePath);
|
|
}
|
|
|
|
private IEnumerator LoadTexture()
|
|
{
|
|
var filePath = Application.streamingAssetsPath.Open(texturePath);
|
|
#if UNITY_IPHONE || UNITY_IOS
|
|
filePath = "file://" + filePath;
|
|
#endif
|
|
var www = new WWW(filePath);
|
|
yield return www;
|
|
var texture = string.IsNullOrEmpty(www.error) ? www.texture : null;
|
|
OnTextureLoad(texture);
|
|
}
|
|
|
|
private void Start()
|
|
{
|
|
if (!string.IsNullOrEmpty(texturePath))
|
|
StartCoroutine(LoadTexture());
|
|
}
|
|
} |