프로젝트

c# chart zoom (X-축 : userSelection 속성 이용, Y-축 : 마우스 스크롤 이용)

BLDC 2020. 2. 5. 16:48

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace chartTest
{
    public partial class Form1 : Form
    {
        public int timer1Tick;
        static int timer1Tick2;
        public Form1()
        {
            InitializeComponent();

            // X-축 zoom : 속성 설정. 마우스 클릭 & 드래그
            chart1.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (cbStop.Checked == false)
            {
                if (timer1Tick < 100)
                    timer1Tick++;
                else
                {
                    chart1.Series[0].Points.RemoveAt(0);
                }
                timer1Tick2++;
                double aa = 2 + Math.Sin(timer1Tick2);
                chart1.Series[0].Points.Add(aa);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

// Y-축 zoom : 마우스 휠 이벤트 이용

            chart1.MouseWheel += MouseWheelOnChart;
        }

        protected void MouseWheelOnChart(object sender, MouseEventArgs e)
        {
            var chart = (Chart)sender;
            var yAxis = chart.ChartAreas[0].AxisY;
            double y, yMin, yMax, yMin2, yMax2;

            yMin = yAxis.ScaleView.ViewMinimum;
            yMax = yAxis.ScaleView.ViewMaximum;
            y = yAxis.PixelPositionToValue(e.Location.Y);

            if (e.Delta < 0) // Scrolled down.
            {
                yMin2 = y - (y - yMin) / 0.9;
                yMax2 = y + (yMax - y) / 0.9;
            }
            else //if (e.Delta > 0) // Scrolled up.
            {
                yMin2 = y - (y - yMin) * 0.9;
                yMax2 = y + (yMax - y) * 0.9;
            }

            if (yMax2 > 5) yMax2 = 5;
            if (yMin2 < 0) yMin2 = 0;

            chart1.ChartAreas[0].AxisY.Maximum = yMax2;
            chart1.ChartAreas[0].AxisY.Minimum = yMin2;
        }

    }
}