单击按钮上的Xamarin.Forms动画(Flash背景)

Ste*_*309 18 c# animation xaml xamarin.forms

我想在我的表单上实现一个拨号盘.现在,在我的XAML中,我正在测试一个按钮:XAML

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
         x:Class="MyXFDemo001.Views.NewItemPage"
         Title="New Item">
<ContentPage.ToolbarItems>
    <ToolbarItem Text="Save" Clicked="Save_Clicked" />
</ContentPage.ToolbarItems>
<ContentPage.Content>
    <StackLayout Spacing="20" Padding="15">
        <Button
            x:Name="buttonSelectContact"
            Clicked="buttonSelectContact_Clicked"
            Text="CLICK" BackgroundColor="#0080ff" />
    </StackLayout>
</ContentPage.Content>
Run Code Online (Sandbox Code Playgroud)

在我的代码后面我有一个方法buttonSelectContact_Clicked:

private async void buttonSelectContact_Clicked(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    btn.BackgroundColor = Color.FromHex("#22ac38");
    await Task.Delay(500);
    btn.BackgroundColor = Color.FromHex("#0080ff");
}
Run Code Online (Sandbox Code Playgroud)

它可以工作,但并不像我想要的那样平稳.你能建议我添加动画而不是这个BackgroundColor吗?

GKM*_*ira 17

我想更好的选择是创建一个可重用的功能来做到这一点.您可以利用中的动画资源.

例如,您可以创建一个扩展方法,为您提供在任何地方重用的简单方法,例如FadeToTranslateTo...

除了在这种特殊情况下平滑地改变颜色的逻辑外,它非常简单.这是代码:

public static class AnimationExtensions
{
    public static Task<bool> ChangeBackgroundColorTo(this Button self, Color newColor, uint length = 250, Easing easing = null)
    {
        Task<bool> ret = new Task<bool>(() => false);

        if (!self.AnimationIsRunning(nameof(ChangeBackgroundColorTo)))
        {
            Color fromColor = self.BackgroundColor;

            try
            {
                Func<double, Color> transform = (t) =>
                  Color.FromRgba(fromColor.R + t * (newColor.R - fromColor.R),
                                 fromColor.G + t * (newColor.G - fromColor.G),
                                 fromColor.B + t * (newColor.B - fromColor.B),
                                 fromColor.A + t * (newColor.A - fromColor.A));

                ret = TransmuteColorAnimation(self, nameof(ChangeBackgroundColorTo), transform, length, easing);
            }
            catch (Exception ex)
            {
                // to supress animation overlapping errors 
                self.BackgroundColor = fromColor;
            }
        }

        return ret;
    }

    private static Task<bool> TransmuteColorAnimation(Button button, string name, Func<double, Color> transform, uint length, Easing easing)
    {
        easing = easing ?? Easing.Linear;
        var taskCompletionSource = new TaskCompletionSource<bool>();

        button.Animate(name, transform, (color) => { button.BackgroundColor = color; }, 16, length, easing, (v, c) => taskCompletionSource.SetResult(c));
        return taskCompletionSource.Task;
    }
}
Run Code Online (Sandbox Code Playgroud)

导入此类(通过using namespace引用)您将能够像下面一样使用它.

声明一个XAML按钮:

<Button Text="Nice button ;)"
        BackgroundColor="Gray"
        x:Name="btnTeste"
        Clicked="btnTest_Click"/>
Run Code Online (Sandbox Code Playgroud)

处理代码隐藏中的处理:

private async void btnTest_Click(object sender, EventArgs args)
{
    #region You will not need this block, it is just to choose a random color for change to
    var colors = new[] { Color.Red, Color.Pink, Color.Silver, Color.Yellow, Color.Black, Color.Green };
    var rnd = new Random();

    var actualColor = btnTeste.BackgroundColor;
    var randomColor = colors.Where(c => c != actualColor).ToArray()[rnd.Next(0, colors.Length - 2)];
    #endregion

    // Here is the effective use of the smooth background color change animation
    await btnTeste.ChangeBackgroundColorTo(randomColor, 150, Easing.CubicOut);
    await btnTeste.ChangeBackgroundColorTo(actualColor, 100, Easing.SinOut);
}
Run Code Online (Sandbox Code Playgroud)

编辑:

结果如下(gif显示点击和双击,因此您可以看到很多平滑的更改):

效果的例子

  • 很好的解决方案,这应该是公认的答案! (2认同)
  • 干得漂亮,我的朋友!而且更简单,没有自定义渲染器! (2认同)

Joh*_*nes 9

根据https://forums.xamarin.com/discussion/58818/how-to-animate-change-of-background-color 你的代码看起来像这样

XAML

<StackLayout Spacing="20" Padding="15">
    <Grid>
        <Button
        x:Name="buttonSelectContactSecond"
        Text="CLICK" BackgroundColor="#22ac38" />
        <Button
            x:Name="buttonSelectContact"
            Clicked="buttonSelectContact_Clicked"
            Text="CLICK" BackgroundColor="#0080ff" />
    </Grid>
</StackLayout>
Run Code Online (Sandbox Code Playgroud)

在代码背后

private async void buttonSelectContact_Clicked(object sender, EventArgs e) 
{
    StartAnimation();
}

private async void StartAnimation()
{
    await Task.Delay(200);
    await buttonSelectContact.FadeTo(0, 250);
    await Task.Delay(200);
    await buttonSelectContact.FadeTo(1, 250);
}
Run Code Online (Sandbox Code Playgroud)


小智 5

您还可以创建带有动画的通用自定义控件:

在这个示例中,我使用了 Image 控件,但您可以使用 Button、Label 等。:)

public class NativeImage : Image
{
    public static readonly BindableProperty CommandProperty =
        BindableProperty.Create(
            nameof(Command),
            typeof(ICommand),
            typeof(NativeImage),
            default(ICommand));

    public ICommand Command
    {
        get => (ICommand) GetValue(CommandProperty);
        set => SetValue(CommandProperty, value);
    }

    public static readonly BindableProperty CommandParameterProperty =
        BindableProperty.Create(
            nameof(Command),
            typeof(object),
            typeof(NativeImage));

    public object CommandParameter
    {
        get => GetValue(CommandParameterProperty);
        set => SetValue(CommandParameterProperty, value);
    }

    private ICommand TransitionCommand
    {
        get
        {
            return new Command(async () =>
            {
                AnchorX = 0.48;
                AnchorY = 0.48;
                await this.ScaleTo(0.8, 50, Easing.Linear);
                await Task.Delay(100);
                await this.ScaleTo(1, 50, Easing.Linear);
                Command?.Execute(CommandParameter);
            });
        }
    }

    public NativeImage()
    {
        Initialize();
    }

    public void Initialize()
    {
        GestureRecognizers.Add(new TapGestureRecognizer
        {
            Command = TransitionCommand
        });
    }
}
Run Code Online (Sandbox Code Playgroud)