UILabel 数字动画

本文介绍了如何在iOS应用中使用UILabel实现数字动态增长的动画效果,详细讲解了实现这一功能的步骤和关键代码,帮助开发者提升用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using UnityEngine;

public class UILabelNumberAnima : MonoBehaviour
{
	public CommonDelegate.VoidDelegate OnAnimaEnd = null;

	UIRichLabel _RichLabel;
	UILabel _Label;

	bool _BeginAnima = false;
	long _CurrentNum = 0;
	long _MaxNum = 0;
	float _AnimaTime = 1.0f;
	float _TotalTime = 0.0f;
	long _CachedNum = 0;
	string _Format = "{0}";

	private void Start()
	{
		Init();
	}

	private void OnDisable()
	{
		_BeginAnima = false;
		_TotalTime = 0.0f;
		enabled = false;
		//Int32 zeroNum = 0;
		//if (_RichLabel != null) _RichLabel.text = zeroNum.ToString();
		//if (_Label != null) _Label.text = zeroNum.ToString();
	}

	private void Update()
	{
		if (!_BeginAnima)
		{
			return;
		}

		_TotalTime += Time.unscaledDeltaTime;
		_CachedNum = (int)(_CurrentNum + _TotalTime * (_MaxNum - _CurrentNum) / _AnimaTime);
		if (_TotalTime >= _AnimaTime)
		{
			if (_RichLabel != null) _RichLabel.text = string.Format(_Format, _MaxNum);
			if (_Label != null) _Label.text = string.Format(_Format, _MaxNum);
			if (OnAnimaEnd != null) OnAnimaEnd();
			OnDisable();
		}
		else
		{
			if (_RichLabel != null) _RichLabel.text = string.Format(_Format, _CachedNum);
			if (_Label != null) _Label.text = string.Format(_Format, _CachedNum);
		}
	}

	public void Init()
	{
		if (_RichLabel == null) _RichLabel = gameObject.GetComponent<UIRichLabel>();
		if (_Label == null) _Label = gameObject.GetComponent<UILabel>();
	}

	public void SetAnima(long currentNum, long maxNum, float animaTime = 1f)
	{
		_CurrentNum = currentNum;
		_MaxNum = maxNum;
		_AnimaTime = animaTime;
		enabled = true;
	}

	public void SetAnimaStr(long currentNum, long maxNum, string format, float animaTime = 1f)
	{
		_CurrentNum = currentNum;
		_MaxNum = maxNum;
		_AnimaTime = animaTime;
		_Format = format;
		enabled = true;
	}

	public void BeginAnima()
	{
		_BeginAnima = true;
		_TotalTime = 0.0f;
		if (_AnimaTime <= 0.0f)
		{
			_AnimaTime = 1.0f;
		}
	}
}

使用方法

_BattleScoreLabel.SetAnima(lastBattleScore, curBattleScore, 0.5f);
_BattleScoreLabel.BeginAnima();


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值