scatter chart와 같은 여러 가지 그래프를 그리는 무료 라이브러인 livechart를 c# wpf에서 사용해보자


Simple, flexible, interactive & powerful charts, maps and gauges for .Net, LiveCharts2 can now practically run everywhere Maui, Uno Platform, Blazor-wasm, WPF, WinForms, Xamarin, Avalonia, WinU...
github.com
beto-rodriguez에게 먼저 감사의 인사를 드린다.
livechart가 stable 버젼으로 1.0이 있긴한데 이게 써보면 알겠지만 느리다. 다른 언어에서는 모르겠지만.
wpf에서 무지막지하게.. 데이터가 5천개만 넘어가도 버벅이기 시작하니 원..
그러나 2.0이 출시되서 소개하는 것이다. 2.0은 1.0과 다르게 빠르다. 가볍고. 매우 쉽게 사용할 수있다.
우선 사용법은 처음 nuget패키지에서 시험판 포함으로 한다음 다운받아야된다.

위와 같이 3개의 패키지가 설치되면 된다.
그다음. 차트를 사용하기 위해 xaml에서 부터
xmlns:lvc="clr-namespace:LiveChartsCore.SkiaSharpView.WPF;assembly=LiveChartsCore.SkiaSharpView.WPF"
위와 같이 첨부하고.
<lvc:CartesianChart Name="Pixelchart" Series="{Binding Series}" XAxes="{Binding XAxes}" YAxes="{Binding YAxes}" Sections="{Binding Sections}" Grid.Row="1" MouseDown="Pixelchart_MouseDown" TooltipPosition="Hidden" EasingFunction="{x:Null}" ZoomMode="X" >
</lvc:CartesianChart>
위와 같이 사용하면 차트를 사용할 준비가 된거다 여기서 차트종류는.

BASIC LINE













위와 같은 것들이 있으니 원하는 기본 플롯을 사용해서 하면 된다.
예시에서는 그냥 basic 라인으로 할 것이다.
이제 xaml에서 원하는 위치에 그래프를 삽입했으면, cs코드에서
using LiveChartsCore;
using LiveChartsCore.Defaults;
using LiveChartsCore.SkiaSharpView;
using LiveChartsCore.SkiaSharpView.Drawing.Geometries;
using LiveChartsCore.SkiaSharpView.Painting;
using SkiaSharp;
using LiveChartsCore.SkiaSharpView.WPF;
using LiveChartsCore.Drawing;
위 라이브러리들을 import하고
xaml에서 바인딩했던 axis나 section들 series들을 아래와 같이 바인딩해준다.
public IEnumerable<ISeries> Series { get; set; }
public Axis[] XAxes { get; set; } =
{
new Axis
{
Name = "axisname",
NamePaint = new SolidColorPaint { Color = SKColors.Black },
SeparatorsPaint = new SolidColorPaint
{
Color = SKColors.Gray,
StrokeThickness = 2
},
MinStep=500,
}
};
public Axis[] YAxes { get; set; } =
{
new Axis
{
Name = "Brightness(level)",
MinStep=64,
NamePaint = new SolidColorPaint { Color = SKColors.Black },
SeparatorsPaint = new SolidColorPaint
{
Color = SKColors.Gray,
StrokeThickness = 2
},
}
};
public ObservableCollection<RectangularSection> Sections { get; set; }= new()
{
new RectangularSection
{
Xi =0,
Xj = 0,
Fill = new SolidColorPaint(new SKColor(255, 0, 0))
}
};
X축과 Y축 이름과 색깔 그리고 두께 그리고 step단위 등등을 같이 바인딩할때 선언해주고,
Section도 우선은 너비가 0부터 0까지 즉 너비 0 색상은 255,0,0으로 해준다(빨간색)
그다음 실제 소스코드에서 Series를 할당해주는데 그냥 basic 라인으로 만들거라 lineseries로 한다.
Series = new ObservableCollection<ISeries>
{
// use the second type argument to specify the geometry to draw for every point
// there are already many predefined geometries in the
// LiveChartsCore.SkiaSharpView.Drawing.Geometries namespace
new LineSeries<ObservablePoint>
{
Values = ValuePixel,
Fill = null,
GeometrySize = 0,
// use the line smoothness property to control the curve
// it goes from 0 to 1
// where 0 is a straight line and 1 the most curved
// LineSmoothness = 0, // mark
GeometryStroke = null,
Stroke = new SolidColorPaint(SKColors.Black, 1),
//Fill = null
}
};
이때 실시간으로 값이 바뀔수 있게 아래와 같이 동기화시키게 선언한뒤
BindingOperations.EnableCollectionSynchronization(ValuePixel, _itemLock1);
물론 먼저 락을 거는 object를 먼저 선언은 해놔야 된다. 전역변수로
Object _itemLock1 = new object();
그다음 이제 차트에 데이터를 더할때는
lock (_itemLock1)
{
ValuePixel.Add(new ObservablePoint(X값,Y값);
}
이런식으로 더하면 된다.
그다음 해당 데이터를 마우스로 클릭할때 값을 알게 이벤트를 추가하려면
private void Pixelchart_MouseDown(object sender, MouseButtonEventArgs e)
{
// checkboxzooom.IsChecked = false;
// Pixelchart.ZoomMode = LiveChartsCore.Measure.ZoomAndPanMode.None;
var chart = (CartesianChart)FindName("Pixelchart");
var p = e.GetPosition(chart);
var scaledPoint = chart.ScaleUIPoint(new LvcPoint((float)p.X, (float)p.Y));
// where the X coordinate is in the first position
var x1 = scaledPoint[0];
//var y = scaledPoint[1];
int near = (int)((int)x1;
int idx = ValuePixel.ToList().FindIndex(x => x.X == near);
this.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
{
if (idx >= 0)
{
ValuePixel[idx].X.ToString();
ValuePixel[idx].Y.ToString();
}
}));
}
위와 같이 찾으면 된다.
이제 실제로 사용하면 아래와 같이 그래프가 생성 된다.

'C# 윈도우 프로그래밍' 카테고리의 다른 글
c# 프로그래밍 mysql/Maria DB 연동하기 (0) | 2023.01.04 |
---|---|
c# 데이터베이스 프로그래밍 (mysql/mssql/oracle) 차이점 (0) | 2023.01.03 |
c# tensorflow object detection(1) (1) | 2022.12.17 |
Geometric model finder C#(2) (0) | 2022.12.17 |
Geometric model finder C#(1) (0) | 2022.12.17 |