要做的程序类似于一个Windows画图程序,也就是“涂鸦板”之类的,因为是基于象素操作的(不是规则几何图形),所以无法把绘图代码放入onPaint事件中处理。现在采用的方法是,使用一个Bitmap作为绘图目标,在OnPaint事件中把这个Bitmap赋给PictureBox。虽然效果达到了,但是有一个问题,就是CPU占用率相当高(双核CPU占用率50%- -),自己分析觉得,大概是onPaint事件中发生了频繁的数据复制之类的,但是找不到解决的方法,所以来向大家求助了。

解决方案 »

  1.   

    正常,gdi+的程序cpu动不动就是40%以上
      

  2.   

    给你个画图的例子(双缓冲),效果很好:
    public partial class DrawLine : Form
    {
    class LineObj
    {
    private Point m_start;
    private Point m_end;
    public LineObj(Point start, Point end)
    {
    this.m_start = start;
    this.m_end = end;
    }
    public void Draw(Graphics g, Pen pen)
    {
    g.DrawLine(pen, m_start, m_end);
    }
    } private Point m_startPoint = Point.Empty;
    List<LineObj> lineList = new List<LineObj>();
    public DrawLine()
    {
    InitializeComponent();
    }
    private void drawLine(Graphics graphics, Point startPoint, Point endPoint)
    {
    BufferedGraphicsContext context = BufferedGraphicsManager.Current;
    BufferedGraphics bg = context.Allocate(graphics, this.ClientRectangle);
    bg.Graphics.Clear(this.BackColor);
    foreach (LineObj line in this.lineList)
    {
    line.Draw(bg.Graphics, SystemPens.ControlText);
    }
    bg.Graphics.DrawLine(SystemPens.ControlText, startPoint, endPoint);
    bg.Render();
    bg.Dispose();
    bg = null;
    }
    protected override void OnPaint(PaintEventArgs e)
    {
    base.OnPaint(e);
    foreach (LineObj line in this.lineList)
    {
    line.Draw(e.Graphics, SystemPens.ControlText);
    }
    }
    protected override void OnMouseDown(MouseEventArgs e)
    {
    base.OnMouseDown(e);
    this.m_startPoint = new Point(e.X, e.Y);
    }
    protected override void OnMouseMove(MouseEventArgs e)
    {
    base.OnMouseMove(e);
    if (e.Button == MouseButtons.Left)
    {
    this.drawLine(this.CreateGraphics(), this.m_startPoint, new Point(e.X, e.Y));
    }
    }
    protected override void OnMouseUp(MouseEventArgs e)
    {
    base.OnMouseUp(e);
    LineObj line = new LineObj(this.m_startPoint, e.Location);
    this.lineList.Add(line);
    }
    }
      

  3.   

    OTL一下,原来CPU使用率高是GDI+的特性啊......to hbxtlhx(平民百姓):我去试一下,感谢~