fc2ブログ

記事一覧

ラベルにアニメーション効果を用いて文字列を表示する方法 | Xamarin.Forms


今回はXamarin.Formsでラベルにアニメーション効果を用いてグラフィカルに文字列を表示する方法についてご紹介いたします。
よくあるのが、金額がカウントアップされて上がっていくようなイメージですね。
今回は既存のアプリ「ExplorerDx」で確認ダイアログを表示せずに、画面上にスキャンした内容を表示する仕様に機能追加してみましたが、ただ単にラベルのテキストを変更しても、ユーザーが気づきにくいところから、アニメーション効果を表示することにより、正しく読取ができていることを確認できると思いました。






前提条件
・Windows10 Pro 64Bit
・Visual Studio 2015 Community Update3
・Xamarin 4.7.9.45 (NuGet Xamarin.Forms 2.4.0.282)
・macOS Sierra 10.12.6 / Xcode 9 / Xamarin.iOS 11.0.0.0



1.PCLの記述

PCLプロジェクト内にアニメーション効果を表示するかどうかを設定できる派生ラベルクラスを作成します。

BaseLabel.cs
using Xamarin.Forms;
namespace AppName.Controls
{
    [System.Diagnostics.DebuggerStepThrough()]
    public class BaseLabel : Label
    {
        public BaseLabel() : base()
        {
        }

        public BaseLabel(bool useAnimation) : base()
        {
            this.UseAnimation = useAnimation;
        }

        public static BindableProperty UseAnimationProperty = BindableProperty.Create(
            propertyName: "UseAnimation",
            returnType: typeof(bool),
            declaringType: typeof(BaseLabel),
            defaultValue: true,
            defaultBindingMode: BindingMode.TwoWay);

        public bool UseAnimation
        {
            get
            {
                return (bool)GetValue(UseAnimationProperty); ;
            }
            set
            {
                SetValue(UseAnimationProperty, value);
            }
        }
    }
}


UseAnimationのプロパティはカスタムレンダラー内でアニメーション効果を設定するかどうかの判断に使用します。



2.iOSの場合

iOSプロジェクト内に以下のカスタムレンダラーを配置します。

CustomLabelRenderer.cs
using System;
using System.ComponentModel;
using CoreAnimation;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using AppName.iOS.Renderer;
using AppName.Controls;
[assembly: ExportRenderer(typeof(BaseLabel), typeof(CustomLabelRenderer))]
namespace AppName.iOS.Renderer
{
public class CustomLabelRenderer : LabelRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
}

protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);

if (Element == null)
{
return;
}

try
{
var view = (BaseLabel)Element;

if (e.PropertyName == BaseLabel.TextProperty.PropertyName &&
view.UseAnimation)
{
//アニメーション設定
CATransition anim = CATransition.CreateAnimation();
anim.Type = CATransition.TransitionMoveIn;
anim.Subtype = CATransition.TransitionFromBottom;
anim.Duration = 0.2f;
Control.Layer.AddAnimation(anim, null);

//テキストを設定
Control.Text = view.Text;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + System.Environment.NewLine +
ex.StackTrace);
}
}
}
}


※文字列を上から下に動かして表示していますが、
Type/SubTypeを変更することによりアニメーションの効果を変更できます。



3.Androidの場合

Androidプロジェクト内に以下のカスタムレンダラーを配置します。

CustomLabelRenderer.cs
using System;
using System.ComponentModel;
using Android.Views.Animations;
using Xamarin.Forms.Platform.Android;
using Xamarin.Forms;
using AppName.Droid.Renderer;
using AppName.Controls;
[assembly: ExportRenderer(typeof(BaseLabel), typeof(CustomLabelRenderer))]
namespace AppName.Droid.Renderer
{
public class CustomLabelRenderer : LabelRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
}

protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);

try
{
if (Element == null)
{
return;
}

var view = (BaseLabel)Element;

if (e.PropertyName == BaseLabel.TextProperty.PropertyName &&
view.UseAnimation)
{
//アニメーション設定
Control.Alpha = 0f; //透過に設定

TranslateAnimation anim = new TranslateAnimation(0, 0, -Control.Height, 0);

anim.Duration = 200;
anim.RepeatCount = 0;
Control.StartAnimation(anim);

Control.Animate().Alpha(1f);
Control.Animate().SetDuration(500);
Control.Animate().SetListener(null);

//テキストを設定
Control.Text = view.Text;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + System.Environment.NewLine +
ex.StackTrace);
}
}
}
}


※文字列を上から下に動かして表示していますが、
TranslateAnimationのコンストラクタに渡す引数を変更することによりアニメーションの効果を変更できます。右から左または左から右に動かす場合はControl.Widthを受け渡すと良いでしょう。



4.使用方法

C#で記述します。アニメーションをONにする場合はコンストラクタの引数にtrueを渡します。あとは、Textプロパティを動的に変更するだけです。
カスタムレンダラーは配置しただけで、簡単に表示方法を変更でき、とても便利です。

TestPage.xaml.cs
using AppName.Services;
using Xamarin.Forms;
public class TestPage : ContentPage
{
private BaseLabel lblAnimationOn = new BaseLabel(true);
private BaseLabel lblAnimationOff = new BaseLabel(false);
void OnButtonClick()
{
    for (int i = 0; i <= 100; i++)
    {
        this.lblAnimationOn.Text = "";
        this.lblAnimationOn.Text = i.ToString();
        this.lblAnimationOff.Text = i.ToString();
    }
}
}


XAMLの場合は以下のように記述します。
TextプロパティはC#で動的に変更してください。

TestPage.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"
             xmlns:base="clr-namespace:AppName.Controls;assembly=AppName"
             x:Class="AppName.Views.TestPage">
  <ContentPage.Content>
    <base:BaseLabel x:Name="lblAnimationOn" Text="" UseAnimation="true"/>
    <base:BaseLabel x:Name="lblAnimationOff" Text="" UseAnimation="false"/>
  </ContentPage.Content>
</ContentPage>






最後までお読みいただきありがとうございます。
当ブログの内容をまとめた Xamarin逆引きメニュー は以下のURLからご覧になれます。
http://itblogdsi.blog.fc2.com/blog-entry-81.html


関連記事

コメント

コメントの投稿

※名前とタイトルが入力されていないコメントでは他のコメントとの区別ができません。

 入力されていないコメントには返信しませんのであらかじめご了承くださいませ。

※ニックネームでも良いので必ずご入力ください。

    

※必ずご入力ください。

    
    

※必ずご入力ください。

※技術的な質問には環境やエラーについて正確かつ詳細にお教えください。

・正確なエラーの内容

・Windowsのバージョン番号

・Visual Studioのバージョン

・機器の型番

・アプリやソフトのバージョン

    

カテゴリ別記事一覧

広告

プロフィール

石河 純


著者名 :石河 純
自己紹介:素人上がりのIT技術者。趣味は卓球・車・ボウリング

IT関連の知識はざっくりとこんな感じです。
【OS関連】
WindowsServer: 2012/2008R2/2003/2000/NT4
Windows: 10/8/7/XP/2000/me/NT4/98
Linux: CentOS RedHatLinux9
Mac: macOS Catalina 10.15 / Mojave 10.14 / High Sierra 10.13 / Sierra 10.12 / OSX Lion 10.7.5 / OSX Snow Leopard 10.6.8
【言語】
VB.net ASP.NET C#.net Java VBA
Xamarin.Forms
【データベース】
Oracle 10g/9i
SQLServer 2016/2008R2/2005/2000
SQLAnywhere 16/11/8
【BI/レポートツール】
Cognos ReportNet (IBM)
Microsoft PowerBI
ActiveReport (GrapeCity)
CrystalReport
【OCX関連】
GrapeCity InputMan SPREAD MultiRow GridView
【ネットワーク関連】
CCNP シスコ技術者認定
Cisco Catalyst シリーズ
Yamaha RTXシリーズ
FireWall関連
【WEB関連】
SEO SEM CSS jQuery IIS6/7 apache2

休みの日は卓球をやっています。
現在、卓球用品通販ショップは休業中です。