【问题标题】:How can i use mouse down click event and paint event of windows forms Chart control to draw points on the chart?如何使用 Windows 窗体图表控件的鼠标按下事件和绘制事件在图表上绘制点?
【发布时间】:2015-05-14 08:56:29
【问题描述】:

我现在添加了起点终点和鼠标 x 和鼠标 y 变量,我想在鼠标左键单击时使用它们在图表控件上绘制点。

但我希望仅在图表区域上绘制点,并且仅当鼠标位于图表中的方形区域内时,它不会在方形边框线或图表控制区域之外绘制点。

当在图表中的方块中移动鼠标时也会显示标签上的 X 轴和 Y 轴值。

左轴 1 到 120 当前时间和下轴 1 到 30 当前天。 因此,如果我在第一个正方形区域中移动鼠标,它应该会显示第 1 天时间 112 或第 2 天时间 33。

这就是为什么我也不确定 X 轴和 Y 轴上的空格是否正确。 它应该是 1 到 120 和 1 到 30,但我认为每个方格都应该在 3 天和 120 时间内出现,但是以 1 的 1 步跳跃,所以当我用鼠标移动时,我可以在第一个方格中看到第 1 天时间 3 或第 3 天时间 66 下一行方块代表第 4 天到第 6 天。

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 Test
{
    public partial class Form1 : Form
    {
        private Point startPoint = new Point();
        private Point endPoint = new Point();
        private int mouseX = 0;
        private int mouseY = 0;

        public Form1()
        {
            InitializeComponent();
        }

        private void chart1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mouseX = System.Windows.Forms.Cursor.Position.X;
                mouseY = System.Windows.Forms.Cursor.Position.Y;
                chart1.Invalidate();

            }
        }

        private void chart1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g1 = this.CreateGraphics();
            Pen linePen = new Pen(Color.Green, 1);
            Pen ellipsePen = new Pen(Color.Red, 1);
            startPoint = new Point(mouseX, mouseY);
            endPoint = new Point(mouseX, mouseY);
            g1.DrawLine(linePen, startPoint, endPoint);
            g1.DrawEllipse(ellipsePen, mouseX - 2, mouseY - 2, 4, 4);
            linePen.Dispose();
            ellipsePen.Dispose();
            g1.Dispose();
        }
    }
}

代码现在的样子,它绘制的点远远超出了图表控制区域。

【问题讨论】:

  • TaW 我在那里尝试了你的解决方案,它确实有效。我拿了你的第二个解决方案代码,我改变了一些东西。而是使用点列表,我只使用了绘制事件中的 lastPoint 变量并且我做到了: e.Graphics.DrawEllipse(pen, lastPoint.X, lastPoint.Y, 4, 4);我这样做是因为我想每次只画一个点。现在的问题是每次单击鼠标时它都会删除最后一个绘制的点。我怎样才能使它不会删除 lastPoint ?
  • 帖子不断将绘制的点添加到数据点集合中。如果您不希望这样并且只绘制一个绘制点,您仍然会将其添加到系列点,或者可能是一个额外的系列;然后您可以计算其正确位置并使用这些坐标设置新点。最后你会删除数据点。我理解对了吗?
  • 你说得对。谢谢。
  • 看看我的answer here。它包含将值点转换为绘图点的通用代码..

标签: c# .net winforms


【解决方案1】:

那是因为您使用了错误的鼠标坐标。 替换这些行

mouseX = System.Windows.Forms.Cursor.Position.X;
mouseY = System.Windows.Forms.Cursor.Position.Y;

有了这个:

mouseX = e.X;
mouseY = e.Y;

System.Windows.Forms.Cursor.Position 以窗体为基础返回鼠标坐标,而MouseEventArgs 以引发事件的控件为基础返回鼠标坐标。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多