LoginSignup
0

More than 5 years have passed since last update.

Xamarin.Formsでスライドショー的なものを作った

Last updated at Posted at 2018-05-28

Taskとか分かってないマンです。とりあえずiOS,Androidで動作確認できたので記述します。

参考サイト

Xamarin.Forms の Device クラスについて(特に Device.OnPlatform)

C# で Thread.Sleep はあきまへん

Taskを極めろ!async/await完全攻略

Twitterで頂いたお言葉

コード

    <ContentView>
        <Image x:Name="img1"/>
    </ContentView>
using System.Threading.Tasks;

public MainPage()
{
    InitializeComponent();

    //スライド用の画像はまず透明にしておく
    img1.Opacity = 0;

    //画像配列を作成
    List<string> imgList = new List<string>();
    imgList.Add("cat1.jpg");
    imgList.Add("cat2.jpg");
    imgList.Add("frog1.jpg");
    imgList.Add("frog2.jpg");

    //配列数取得、配列は0からなのでデクリメント
    int imgCount = imgList.Count;
    imgCount--;

    //参照する配列番号
    int imgNum = 0;

    //タスク
    async Task Slideshow()
    {
        //画像パスの作成※"test.img."はプロジェクト名.ディレクトリ名 です
        String ImagePath = "test.img." + imgList[imgNum];
        //画像を反映※最初に1度だけ通ること前提処理
        this.img1.Source = ImageSource.FromResource(ImagePath);

        //画像がループするようにする
        while (true)
        {                              
            var nextImgNum = await Task.Run(async () =>
            {                     
                //3000ミリ秒かけて徐々にスライド画像を不透明に
                await img1.FadeTo(1, 3000);
                //3000ミリ秒かけて徐々にスライド画像を透明に
                await img1.FadeTo(0, 3000);
                //次の画像のインデックス
                imgNum++;

                //もし、ネクストインデックスが画像配列に存在しない数値だった場合0に戻す
                if(imgCount < imgNum){
                    imgNum = 0;
                }

                //次に参照する画像パス       
                var num = "test.img." + imgList[imgNum];                  
                return num.ToString();                  
            });

            //UIスレッドに戻す処理
            Device.BeginInvokeOnMainThread(() => {
                //画像を反映
                this.img1.Source = ImageSource.FromResource(nextImgNum);
            });
        }            
    }

    //Taskの開始
    Task startupWork = new Task(() => { Slideshow(); });
    startupWork.Start();
}

分からない部分

Warningが一箇所出ています

Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.

Screen Shot 2018-05-28 at 18.00.06.png

指摘やアドバイスがあれば是非お願いします

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0