Unity4.6 UI实现渐隐渐现(FadeIn FadeOut)效果

 

在做UI后期设计时,我们可能要对UI做一些特效,这篇文章我们来学习下如何在Unity3d中对实现渐隐渐现的效果,

首先我们看下Unity New UI即UGUI中渐隐渐现的做法.

观察我们会发现Unity4.6 UI中每个能够显示控件都会有一个CanvasRender对象,CanvasRender有什么作用呢,我们

看下官方的解释:The Canvas Renderer component renders a graphical UI object contained within a Canvas.简单的

翻译过来就是,画布上的渲染器组件将呈现包含在一个画布内的图形用户界面对象,再仔细查看CanvasRenderer类

时我们可以看到有两个方法SetAlpha ,SetColor,显然我们可以修改透明度Alpha和Color来实现渐隐渐现,同时我

们还可以发现Button,Text,Image等控件都会集成自Unity.UI.Graphic

如下所示:


public class Text : MaskableGraphic, ILayoutElement

public abstract class MaskableGraphic : Graphic, IMaskable

public class Image : MaskableGraphic, ICanvasRaycastFilter, ISerializationCallbackReceiver, ILayoutElement

然后我们再阅读Graphic代码,我们会发现有两个方法


public void CrossFadeAlpha(float alpha, float duration, bool ignoreTimeScale);
public void CrossFadeColor(Color targetColor, float duration, bool ignoreTimeScale, bool useAlpha);

开源源码如下:


public void CrossFadeAlpha(float alpha, float duration, bool ignoreTimeScale)
{
CrossFadeColor(CreateColorFromAlpha(alpha), duration, ignoreTimeScale, true, false);
}

public void CrossFadeColor(Color targetColor, float duration, bool ignoreTimeScale, bool useAlpha)
{
CrossFadeColor(targetColor, duration, ignoreTimeScale, useAlpha, true);
}

private void CrossFadeColor(Color targetColor, float duration, bool ignoreTimeScale, bool useAlpha, bool useRGB)
{
if (canvasRenderer == null || (!useRGB && !useAlpha))
return;

Color currentColor = canvasRenderer.GetColor();
if (currentColor.Equals(targetColor))
return;

ColorTween.ColorTweenMode mode = (useRGB && useAlpha ?
ColorTween.ColorTweenMode.All :
(useRGB ? ColorTween.ColorTweenMode.RGB : ColorTween.ColorTweenMode.Alpha));

var colorTween = new ColorTween {duration = duration, startColor = canvasRenderer.GetColor(), targetColor = targetColor};
colorTween.AddOnChangedCallback(canvasRenderer.SetColor);
colorTween.ignoreTimeScale = ignoreTimeScale;
colorTween.tweenMode = mode;
m_ColorTweenRunner.StartTween(colorTween);
}

因此我们利用CrossFadeColor或CrossFadeAlpha这两个方法就可以实现渐隐渐现了

下面是客户端调用代码


void Start()
{

Component[] comps = GameObject.Find("/Canvas").GetComponentsInChildren<Component>();
foreach (Component c in comps)
{
if (c is Graphic)
{
(c as Graphic).CrossFadeAlpha(0, 1, true);
}

}
}

执行的效果就是所有Canvas下的元素都在1秒之类执行淡出效果,本篇到此结束,谢谢围观!