YanCheng_Metrology/Assets/Scripts/Project/Objects/Other/ImageTips.cs

71 lines
2.0 KiB
C#

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
/// <summary>
/// UI提示
/// </summary>
public class ImageTips : MonoBehaviour
{
private Image image; // UI Image组件
public float fadeDuration = 1.0f; // 每次淡入淡出的持续时间
private RectTransform selfRect;
public Vector2 sizeOffset = new Vector2(100, 100);
public void ShowTips(RectTransform target)
{
gameObject.SetActive(true);
selfRect = GetComponent<RectTransform>();
image = GetComponent<Image>();
image.enabled = true;
selfRect.SetParent(target);
selfRect.anchorMin = Vector2.zero;
selfRect.anchorMax = new Vector2(1, 1);
selfRect.offsetMax = Vector2.zero;
selfRect.offsetMin = Vector2.zero;
//selfRect.sizeDelta = target.sizeDelta + sizeOffset;
if (gameObject.activeSelf && gameObject.activeInHierarchy)
StartCoroutine(FlashRoutine());
}
public void HideTips()
{
transform.parent = null;
if (gameObject.activeSelf && gameObject.activeInHierarchy)
{
StopCoroutine(FlashRoutine());
gameObject.SetActive(false);
}
}
private IEnumerator FlashRoutine()
{
while (true)
{
yield return StartCoroutine(Fade(1.0f, fadeDuration));
yield return StartCoroutine(Fade(0.0f, fadeDuration));
}
}
private IEnumerator Fade(float targetAlpha, float duration)
{
float startAlpha = image.color.a;
float elapsed = 0.0f;
while (elapsed < duration)
{
elapsed += Time.deltaTime;
float newAlpha = Mathf.Lerp(startAlpha, targetAlpha, elapsed / duration);
Color color = image.color;
color.a = newAlpha;
image.color = color;
yield return null;
}
// 确保最终值准确
Color finalColor = image.color;
finalColor.a = targetAlpha;
image.color = finalColor;
}
}