かずきのBlog@hatena

すきな言語は C# + XAML の組み合わせ。Azure Functions も好き。最近は Go 言語勉強中。日本マイクロソフトで働いていますが、ここに書いていることは個人的なメモなので会社の公式見解ではありません。

Xamarin.Formsでグラフを描こう(OxyPlot)

WPFでグラフを描けるライブラリを探してたらOxyPlotというのを見つけました。 見つけたと思ったら、こいつXamarin.Formsでもできるぞ!?ということで試して見ました。

NuGetの追加

以下のパッケージを追加します。

  • OxyPlot.Xamarin.Forms

初期化

以下のコードをXamarin.Forms.Forms.Init()の後に追加します。

PlotViewRenderer.Init();

画面構築

画面にPlotView部品を置きます。そしてModelプロパティをバインドします。

<?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:local="clr-namespace:OxyApp"
    xmlns:oxy="clr-namespace:OxyPlot.Xamarin.Forms;assembly=OxyPlot.Xamarin.Forms"
    x:Class="OxyApp.OxyAppPage">
    <ContentPage.BindingContext>
        <local:OxyAppPageViewModel />
    </ContentPage.BindingContext>
    <oxy:PlotView Model="{Binding Model}" />
</ContentPage>

ViewModelの構築

ViewModelでグラフのモデルを構築します。

using System;
using OxyPlot;
using OxyPlot.Series;

namespace OxyApp
{
    public class OxyAppPageViewModel
    {
        public PlotModel Model { get; }

        public OxyAppPageViewModel()
        {
            this.Model = new PlotModel { Title = "Hello OxyPlot" };
            this.Model.Series.Add(new LineSeries
            {
                Points =
                {
                    new DataPoint(0, 10),
                    new DataPoint(1, 20),
                    new DataPoint(2, 15),
                    new DataPoint(3, 40),
                }
            });
        }
    }
}

Seriesにグラフの種類を表すSeries(今回の場合は折れ線グラフ)を追加していく形になります。DataPointをPointsに追加することで折れ線のデータを指定できます。

実行して動作確認

こんな感じで表示されます。

f:id:okazuki:20170116083107p:plain

感想

パッと触った感じ、なかなかいいんじゃないんでしょうか?? ライセンスもMITで扱いやすそう。