D.Man
D.Man

Reputation: 293

How do I correctly set the duration for a WPF TextBlock DoubleAnimation to maintain the same speed when the text length varies when changed?

How do I correctly set the duration for a WPF TextBlock DoubleAnimation to maintain the same speed when the text length varies when changed?

So in the code below, the marquee runs to complete the entire string of text once. On the completed event, the text changes, which simulates when the feed would change. The marquee is then restarted.

However, the duration for the DoubleAnimation needs to maintain a constant speed, irrespective of the string length of the text content.

How do I correctly calculate this?

It's not as simple as a value for 1 character * the text length.

I have tried looking this up but have not found an answer to this.

Any help greately appreciated.

Here is all the code...

The xaml - MainWindow.xaml:

<Window x:Name="MainWin" x:Class="MarqueeWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        
        xmlns:local="clr-namespace:MarqueeWPF"
        mc:Ignorable="d"
        Title="" Height="35" Width="800"
        Background="#404040"
        ResizeMode="NoResize"
        AllowsTransparency="False"
        WindowStyle="None"
        Topmost="false"
        Left="0"
        Top="0"
        Foreground="WhiteSmoke"
        FontFamily="Ariel"
        FontSize="12"
        
        ShowInTaskbar="False"
        WindowStartupLocation="Manual"
        WindowState="Normal"
        MaxHeight="36"
        Loaded="_onLoaded"
        Closing="_onClosing"
        
        >

    <Canvas ClipToBounds="False"
                 Name="canMain"
                 MaxHeight="35"         
                 Background="#303030"
                 
                 Height="35">
        <TextBlock  Name="tbmarquee" 
                        Text="Shrek 5: Mike Myers, Eddie Murphy and Cameron Diaz to return for new film - BBC.com | Ben Affleck's daughter Violet reveals why she wears face mask in public in sad admission - The Mirror | Dinosaur unearthed on Isle of Wight identified as new plant-eating species - The Guardian | Keir Starmer says defence spending commitment 'cast iron' - but refuses to give timeline - BBC.com | Two children from Liverpool primary school dealing with infection outbreak have died - Sky News | England vs Netherlands LIVE: Updates and team news ahead of Euro 2024 semi-final - The Independent | Almost half Tory members want merger with Reform UK, poll suggests, as leadership infighting escalates – UK politics live - The Guardian | Samsung Electronics workers to extend strike indefinitely - The Guardian | Hip-hop band Cypress Hill makes 1996 Simpsons joke come true - The Guardian | Police search for man after three women killed in Bushey - The Guardian | Israel-Hamas war: Dozens killed in Israeli airstrike outside school in Gaza - Sky News | Barratt shares drop as it warns it will build fewer homes this year; Britons spend on days out over DIY – business live - The Guardian | Sugar tax cut adult intake by two teaspoons a day - The Times | Kylian Mbappe issues damning verdict on France 'failure' after Euro 2024 howler - The Mirror | Nick Kyrgios comes up with brilliant new nickname for Daniil Medvedev at Wimbledon - Express | Jay Slater's family break silence after Tenerife police say he is NOT ‘missing feared dead’ -Birmingham Live | New FLiRT Covid variant spreading across the UK as doctors issue summer warning - The Independent | New Manchester United bid incoming, Ineos are determined to land Erik ten Hag's key target - United In Focus - Manchester United FC News | Type of Russian missile that struck Kyiv children’s hospital uses western components - Financial Times | How Le Pen’s far right blew it - POLITICO Europe "
                            FontSize="18"
                            FontFamily="Ariel"
                            FontWeight="Normal"
                            Foreground="WhiteSmoke" 
                            
                            RenderOptions.BitmapScalingMode="HighQuality" 
                            Canvas.Top="2"></TextBlock>
    </Canvas>
    
</Window>

The code-behind - MainWindow.xaml.cs:

using System.Diagnostics;
using System.Net.Http;
using System.Windows;
using System.Windows.Controls;
using Newtonsoft.Json.Linq;
using System.Windows.Media.Animation;

namespace MarqueeWPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private double _marqueeTimeInSeconds = 40;
        private string _testText = "";
        private int _completedCount;

        public MainWindow()
        {
            InitializeComponent();

            Width = SystemParameters.PrimaryScreenWidth;
            Top = 0;
        }

        private void _onLoaded(object sender, RoutedEventArgs e)
        {
            _testText = "Shrek 5: Mike Myers, Eddie Murphy and Cameron Diaz to return for new film - BBC.com | Ben Affleck's daughter Violet reveals why she wears face mask in public in sad admission - The Mirror | Dinosaur unearthed on Isle of Wight identified as new plant-eating species - The Guardian | Keir Starmer says defence spending commitment 'cast iron' - but refuses to give timeline - BBC.com | Two children from Liverpool primary school dealing with infection outbreak have died - Sky News | England vs Netherlands LIVE: Updates and team news ahead of Euro 2024 semi-final - The Independent | Almost half Tory members want merger with Reform UK, poll suggests, as leadership infighting escalates – UK politics live - The Guardian | Samsung Electronics workers to extend strike indefinitely - The Guardian | Hip-hop band Cypress Hill makes 1996 Simpsons joke come true - The Guardian | Police search for man after three women killed in Bushey - The Guardian | Israel-Hamas war: Dozens killed in Israeli airstrike outside school in Gaza - Sky News | Barratt shares drop as it warns it will build fewer homes this year; Britons spend on days out over DIY – business live - The Guardian | Sugar tax cut adult intake by two teaspoons a day - The Times | Kylian Mbappe issues damning verdict on France 'failure' after Euro 2024 howler - The Mirror | Nick Kyrgios comes up with brilliant new nickname for Daniil Medvedev at Wimbledon - Express | Jay Slater's family break silence after Tenerife police say he is NOT ‘missing feared dead’ -Birmingham Live | New FLiRT Covid variant spreading across the UK as doctors issue summer warning - The Independent | New Manchester United bid incoming, Ineos are determined to land Erik ten Hag's key target - United In Focus - Manchester United FC News | Type of Russian missile that struck Kyiv children’s hospital uses western components - Financial Times | How Le Pen’s far right blew it - POLITICO Europe ";

            tbmarquee.Text = _testText;
            tbmarquee.UpdateLayout();
            
            _marqueeTimeInSeconds = 5; // secs; // 160;

            Canvas.SetRight(canMain, SystemParameters.PrimaryScreenWidth);

            RightToLeftMarquee();
        }
        
        private void _onClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
        }

        private void RightToLeftMarquee()
        {
            tbmarquee.Text = _testText;
            tbmarquee.UpdateLayout();

            DoubleAnimation doubleAnimation = new DoubleAnimation();
            doubleAnimation.Completed += _doubleAnimation_Completed;
            double height = canMain.ActualHeight - tbmarquee.ActualHeight;
            tbmarquee.Margin = new Thickness(0, height / 2, 0, 0);
            
            doubleAnimation.From = -tbmarquee.ActualWidth;
            doubleAnimation.To = canMain.ActualWidth;
            //doubleAnimation.RepeatBehavior = RepeatBehavior.Forever;
            
            doubleAnimation.Duration = new
                    Duration(TimeSpan.FromSeconds(_marqueeTimeInSeconds));
            tbmarquee.BeginAnimation(Canvas.RightProperty, doubleAnimation);
        }

        private void _doubleAnimation_Completed(object? sender, EventArgs e)
        {
            _completedCount++;

            // Change after first complete
            if (_completedCount == 1)
            {
                // comment/uncomment for different test cases
                // 1. reverse text for test purposes
                //_testText = ReverseString(_testText);

                // 2. make text longer for test purposes
                _testText = _testText + _testText.Substring(0, _testText.Length / 2);

                // 3. make text much longer for test purposes
                //_testText = _testText + _testText + _testText + _testText + _testText + _testText  + _testText + _testText + _testText + _testText + _testText;

                // 4. make text shorter for test purposes
                //_testText = _testText.Substring(0, _testText.Length / 2);

                // 5. one character test
                // _testText = _testText[..1];

                _marqueeTimeInSeconds = 450; // ???? How to calculate this?

                RightToLeftMarquee();
            }
        }

        private string ReverseString(string text)
        {
            var a = text.ToCharArray();
            Array.Reverse(a);
            var result = new string(a);
            return result;
        }
    }
}

Update 17/07/2024:

So, I have this working now by setting the duration like this:

doubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(
                                     (tbmarquee.ActualWidth + canMain.ActualWidth) * _speedFactor));

_speedFactor is a double used to change the speed. It works okay but the next part of this is how to make the marquee continuous.

Update 18/07/2024:

What I need to do with this now is have an updated string of data directly follow on from the original (such as an updated news feed). And then for this to cycle in this fashion continously. So there would be no gap between the first string and the second string, i.e. no waiting for the first string to be completely off the screen on the lhs. Obviously, the strings would be different lengths.

So, as soon as the end of the first string/textblock/label has been scrolled into view on the rhs, the second one should immediately follow seamlessly, scrolling in smoothly from the rhs, as though it's just one continuous stream.

I have tried to find how to do this but have been unsuccessful.

Does anyone know how to achieve this?

I would appreciate any help.

Upvotes: 0

Views: 44

Answers (0)

Related Questions