차트 컨트롤은 데이터의 추이 및 통계데이터를 볼때 사용됩니다.

차트는 많은 컴포넌트들이 있으며 유료도 존재합니다.

제가 여기서 소개할것은 무료인 OxyPlot 차트 입니다.

oxyplot 는 자마린 뿐만 아니라 윈폼용, WPF 용도 있습니다.

제가 테스트해본 결과는 ios, android, uwp 모두 잘 동작합니다.

이번 포스팅에서는 간단하게 바(bar)차트를 하나 그려보겠습니다.

추후 차트쪽은 계속 포스팅이 될수도 있을것 같습니다.

 

1. 이식가능 프로젝트에 oxyplot 를 nuget 에서 설치합니다.

oxyplot 로 검색하면 OxyPlot.Xamarin.Forms 가 있습니다. 이걸 설치합니다.

'확인' 하고

 

설치완료.

 

2. Android , IOS, UWP 등의 각 프로젝트에도 Nuget 을 통해 OxyPlot.Xamarin.Forms 를 설치합니다.

Android

iOS

UWP

 

3. 각 장치에 따른 코딩 추가

이식 가능 프로젝틑 제외한 각 장치 프로젝트에서 OxyPlot 을 초기화하는 함수를 반드시 호출해 주어야합니다.

Android (MainActivity.cs)

        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(bundle);

            global::Xamarin.Forms.Forms.Init(this, bundle);
            OxyPlot.Xamarin.Forms.Platform.Android.PlotViewRenderer.Init();
            LoadApplication(new App());
        }

iOS (AppDelegate.cs)

        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            OxyPlot.Xamarin.Forms.Platform.iOS.PlotViewRenderer.Init();
            LoadApplication(new App());

            return base.FinishedLaunching(app, options);
        }

UWP (App.xaml)

protected override void OnLaunched(LaunchActivatedEventArgs e)
        {

#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                Xamarin.Forms.Forms.Init(e);
                OxyPlot.Xamarin.Forms.Platform.UWP.PlotViewRenderer.Init();

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                rootFrame.Navigate(typeof(MainPage), e.Arguments);
            }
            // Ensure the current window is active
            Window.Current.Activate();
        }

이제 환경구성은 완료

 

4. 차트를 생성합니다.

Content Page 를 하나 만듭니다.  (OxyPlottPage.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:oxy="clr-namespace:OxyPlot.Xamarin.Forms;assembly=OxyPlot.Xamarin.Forms"
             x:Class="XamarinFormsStudy.OxyPlotPage">
        <Grid>
            <oxy:PlotView x:Name ="PlotChart"
                      VerticalOptions="Center"
                      HorizontalOptions="Center"/>
        </Grid>
</ContentPage>

차트에 데이터를 채웁니다.

using OxyPlot;
using OxyPlot.Axes;
using OxyPlot.Series;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace XamarinFormsStudy
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class OxyPlotPage : ContentPage
    {
        public OxyPlotPage()
        {
            InitializeComponent();
            CreateBarChart(false,"OxyPlot BarChart");
        }

        private void CreateBarChart(bool stacked, string title)
        {
            var model = new PlotModel
            {
                Title = title,
                LegendPlacement = LegendPlacement.Outside,
                LegendPosition = LegendPosition.BottomCenter,
                LegendOrientation = LegendOrientation.Horizontal,
                LegendBorderThickness = 0
            };

            var s1 = new BarSeries { Title = "Series 1", IsStacked = stacked, StrokeColor = OxyColors.Black, StrokeThickness = 1 };
            s1.Items.Add(new BarItem { Value = 25 });
            s1.Items.Add(new BarItem { Value = 137 });
            s1.Items.Add(new BarItem { Value = 18 });
            s1.Items.Add(new BarItem { Value = 40 });

            var s2 = new BarSeries { Title = "Series 2", IsStacked = stacked, StrokeColor = OxyColors.Black, StrokeThickness = 1 };
            s2.Items.Add(new BarItem { Value = 12 });
            s2.Items.Add(new BarItem { Value = 14 });
            s2.Items.Add(new BarItem { Value = 120 });
            s2.Items.Add(new BarItem { Value = 26 });

            var categoryAxis = new CategoryAxis { Position = CategoryAxisPosition() };
            categoryAxis.Labels.Add("Category A");
            categoryAxis.Labels.Add("Category B");
            categoryAxis.Labels.Add("Category C");
            categoryAxis.Labels.Add("Category D");
            var valueAxis = new LinearAxis { Position = ValueAxisPosition(), MinimumPadding = 0, MaximumPadding = 0.06, AbsoluteMinimum = 0 };
            model.Series.Add(s1);
            model.Series.Add(s2);
            model.Axes.Add(categoryAxis);
            model.Axes.Add(valueAxis);

            PlotChart.Model = model;
        }

        private AxisPosition CategoryAxisPosition()
        {
            if (typeof(BarSeries) == typeof(ColumnSeries))
            {
                return AxisPosition.Bottom;
            }

            return AxisPosition.Left;
        }

        private AxisPosition ValueAxisPosition()
        {
            if (typeof(BarSeries) == typeof(ColumnSeries))
            {
                return AxisPosition.Left;
            }

            return AxisPosition.Bottom;
        }
    }
}

App.xaml 에서 이제 위에서 만든 XplotPage.xaml 를 호출해 줘야겠죠

        public App()
        {
            InitializeComponent();

            MainPage = new XamarinFormsStudy.OxyPlotPage();
        }

결과

 

각각의 세부설명은 추후 포스팅에서 더 다루도록 하겠습니다.

 

참고

https://www.codeproject.com/Articles/1167724/Using-OxyPlot-with-Xamarin-Forms

http://docs.oxyplot.org/en/latest/getting-started/hello-xamarin-forms.html

https://github.com/oxyplot/oxyplot

GitHub > https://github.com/knagjun/XamarinForms

+ Recent posts