【问题标题】:Chart paint event图表绘制事件
【发布时间】:2015-06-29 01:36:40
【问题描述】:

这是我正在运行的代码:

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

namespace ChartTeste
{
    public partial class Form1 : Form
    {
        Graphics g;

        public Form1()
        {
            InitializeComponent();
            chart1.ChartAreas["Triangulos"].AxisY.Minimum = 0;
            chart1.ChartAreas["Triangulos"].AxisY.Maximum = 40;
            chart1.ChartAreas["Triangulos"].AxisX.Minimum = 0;
            chart1.ChartAreas["Triangulos"].AxisX.Maximum = 5;
            g = chart1.CreateGraphics();
        }

        private void chart1_Paint(object sender, PaintEventArgs e)
        {
            Paint();
        }

        private void Paint()
        {
            Pen p = new Pen(Brushes.Red);
                chart1.Series["PreçoT"].Points.AddXY(1, 0);

                double posiX = chart1.ChartAreas["Triangulos"].AxisX.ValueToPixelPosition(1);
                double posiY = chart1.ChartAreas["Triangulos"].AxisY.ValueToPixelPosition(13);
                double posiY2 = chart1.ChartAreas["Triangulos"].AxisY.ValueToPixelPosition(16);
                double max = chart1.ChartAreas["Triangulos"].AxisY.ValueToPixelPosition(19);
                double min = chart1.ChartAreas["Triangulos"].AxisY.ValueToPixelPosition(10);


                Point[] points = { new Point(Convert.ToInt32(posiX - 20), Convert.ToInt32(posiY)), new Point(Convert.ToInt32(posiX + 20), Convert.ToInt32(posiY)), new Point(Convert.ToInt32(posiX + 20), Convert.ToInt32(posiY2)) };

                g.DrawLine(p,Convert.ToInt32(posiX),Convert.ToInt32(min),Convert.ToInt32(posiX),Convert.ToInt32(max));
                g.FillPolygon(Brushes.Red, points);
        }
    }
}

当我运行它时,生成的三角形不固定,它闪烁并出现故障。有什么方法可以在生成三角形后停止 Paint 事件?

感谢任何帮助。

【问题讨论】:

  • 如果你只需要代码执行一次,你为什么要把它放在图表的绘制事件中?为什么不将其添加到构造函数中?
  • Paint 事件很危险。它运行了很多次,这就是为什么你有这个闪烁。试着把它放在Invalidated
  • @wazaaaap 因为我在整个程序中不会只做一次。此代码用于演示目的。我将创建一个方法来每 x 分钟加点。另外,如果我把它放在构造函数中,我会得到一个 nullPointer
  • 从不,从不使用 CreateGraphics() 来绘制。它“出现故障”是因为您将像素直接溅到屏幕上。由于 Chart 控件使用双缓冲,它们将很快再次被重绘。始终使用e.Graphics,将其传递给您的 Paint() 方法。
  • 谢谢@HansPassant,但是如何给三角形的内部着色?

标签: c# winforms events charts


【解决方案1】:
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
【解决方案2】:

要停止闪烁,请将 this.DoubleBuffered = true; 添加到表单的构造函数中。
要每 X 分钟重新绘制一次表单,请在计时器滴答事件中添加 Invalidate(true);(我假设您有计时器)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 2017-01-26
    • 2012-11-13
    相关资源
    最近更新 更多