'TextBlock Animation'에 해당되는 글 1건

  1. 2010.03.11 [ WPF ] 옆으로 흐르는 TextBlock
Window/WPF2010. 3. 11. 18:09

이번 포스팅에서는

TV를 보면 자막이 옆으로 흐르는 것 같은 애니메이션을

TextBlock을 이용해 비하인드 코드로 구현하는 방법에 대해 알아보겠습니다.

 

예제는 다음과 같이 Grid와 Canvas에 대해 작성해 보았습니다.

 

 

주의 할 점은 Grid 패널은 자식 요소의 크기를

자신의 크기에 맞게 변경해 버리기 때문에 Text 의 길이가 Grid 패널의

사이즈를 넘어 갈 경우 짤리는 현상이 발생합니다.

 

이를 방지 하기 위해 오버되는 Text의 길이 만큼 Margin 의 Right 값을 변경합니다.

 

소스는 다음과 같습니다.

간단히 TranslateTransform 의 x 값을 변경하는 내용입니다.

  private void TranslateAnimation(TextBlock text, double time)

 {

    double right = 0;

    FrameworkElement parent = text.Parent as FrameworkElement;

 

    // 텍스트의 길이가 부모 패널을 넘어갈 때

    if (text.ActualWidth > parent.ActualWidth)

    {

        right = text.ActualWidth - parent.ActualWidth;

    }

 

    // 부모 패널이 Grid라면 Margin 값 변경

    // 텍스트가 잘리는 현상 방지

    if (parent is Grid)

    {

        text.Margin = new Thickness(0, 0, -right, 0);

    }

 

    // TranslateTransform을 생성해야 애니메이션 적용

    text.RenderTransform = new TranslateTransform();

 

    Storyboard story = new Storyboard();

 

    DoubleAnimation animation = new DoubleAnimation();

 

    animation.From = parent.ActualWidth;

    animation.To = -(parent.ActualWidth + right);

    animation.Duration = TimeSpan.FromSeconds(time);

    animation.RepeatBehavior = RepeatBehavior.Forever;

 

    // TranslateTransform.XProperty 값 설정

    DependencyProperty[] Dproperty = new DependencyProperty[]

    {

        TextBlock.RenderTransformProperty,

        TranslateTransform.XProperty

    };

 

    string path = "(0).(1)";

 

    Storyboard.SetTargetProperty(animation, new PropertyPath(path, Dproperty));

    story.Children.Add(animation);

    story.Begin(text);

 }

 

'Window > WPF' 카테고리의 다른 글

[ WPF ] 캡쳐보드 카메라 사용하기  (0) 2010.04.22
[ WPF ] Using WPF in Winform  (0) 2010.03.12
[ WPF ] Page간 데이터 전달  (0) 2010.03.06
[ WPF ] 간단한 Image Animation  (2) 2010.02.12
[ WPF ] Canvas Image Background  (0) 2010.02.11
Posted by 열ㅇl