.NET MAUI颜色动画问题:按钮背景色无过渡直接变白
问题原因及解决方案
问题原因
你这段代码里背景色动画跳过过渡直接变白的核心问题是对Color.FromRgb方法的参数范围理解错误:
Xamarin.Forms的Color.FromRgb()方法接收的是0到1之间的浮点数(代表颜色通道的强度比例),而非0到255的整数。你的代码中把动画值x(从0到255)直接传入,当x大于1时,方法会自动截断为1,导致动画一开始就直接跳到白色((1,1,1)对应白色),完全跳过中间过渡阶段。
修复方案
将颜色通道数值转换为0-1的浮点数范围,有两种常用实现方式:
方式一:调整动画起止值为0到1
直接匹配FromRgb的参数要求,修改背景色动画代码:
{ 0, 1, new Animation((x) => sender.BackgroundColor = Color.FromRgb(x, x, x), 0, 1) }
这种方式下,动画会从黑色(0,0,0)平滑过渡到白色(1,1,1)。
方式二:保留0-255范围,回调时做浮点数除法
如果想维持原有的数值范围,在赋值时将x除以255(注意用255f确保浮点数除法):
{ 0, 1, new Animation((x) => sender.BackgroundColor = Color.FromRgb(x/255f, x/255f, x/255f), 0, 255) }
完整修复后的代码示例
namespace BucketList { class ButtonAnimation : TriggerAction<Button> { protected override async void Invoke(Button sender) { var animation = new Animation() { { 0, 1, new Animation((x) => sender.FontSize = x, 20, 32) }, { 0, 1, new Animation((x) => sender.Rotation = x, 0, 360, easing: Easing.SpringIn) }, // 使用方式一修复背景色动画 { 0, 1, new Animation((x) => sender.BackgroundColor = Color.FromRgb(x, x, x), 0, 1) } }; animation.Commit(sender, "ComplexAnimation", length: 2500, repeat: () => true); } } }
内容的提问来源于stack exchange,提问作者luvairo
相关产品推荐
相关产品推荐

