C# winform 高效绘图

最近工作中需要给一个网络视频会议c++ sdk编写winform客户端 demo,其中的有个功能为电子白板,初步了解下C#绘图相关的基础知识。

由于在绘制连续点组成的曲线时鼠标移动的速度非常快,所以要考虑效率,否则会漏掉很多点,导致曲线不够自然。

绘图使用的组件为 PictureBox ,变量名为 pictureBox_draw。 

基本思路是在PictureBox上绘制过程(MouseMove中),在Image上绘制最终结果(MouseUp),最后设置 pictureBox_draw.Image = mDrawedImg

片段代码如下:

private Graphics mCurrentGraph;    //PictureBox组件对应的Graphics
private Pen mPen = new Pen(Color.FromArgb(0,0,0), 3); //绘图的画笔

private Image mDrawedImg;     //用来保存最终的绘制结果的图片
private Graphics mImgGraph;   //mDrawedImg的Graphics

//.........

{
    mCurrentGraph = pictureBox_draw.CreateGraphics();
    mCurrentGraph.SmoothingMode = SmoothingMode.AntiAlias;   //抗锯齿

    mDrawedImg = new Bitmap(pictureBox_draw.Width, pictureBox_draw.Height); //初始化为空白图片
    mImgGraph = Graphics.FromImage(mDrawedImg);            
    mImgGraph.SmoothingMode = SmoothingMode.AntiAlias;
}


private PointF mLastPoint;
private List<PointF> mPoints = new List<PointF>();
private void pictureBox_draw_MouseDown(object sender, MouseEventArgs e)
{
    mIsDrawing = true;
    mLastPoint = new PointF(e.X, e.Y);           

    if(mType == "Dot")
    {
        mPoints.Add(mLastPoint); 
    }
    else if(mType == "Line")
    {
       
    }
}

private void pictureBox_draw_MouseMove(object sender, MouseEventArgs e)
{
    if (mIsDrawing == false)
        return;

    PointF currentPoint = new PointF(e.X, e.Y);

    if(mType == "Dot")
    {                
        mCurrentGraph.DrawLine(mPen, mLastPoint, currentPoint);

        mLastPoint = currentPoint;
        mPoints.Add(currentPoint);                
    }
    else if(mType == "Line")
    {
        pictureBox_draw.Refresh();
        mCurrentGraph.DrawLine(mPen, mLastPoint, currentPoint);
    }
}

private void pictureBox_draw_MouseUp(object sender, MouseEventArgs e)
{
    if (mIsDrawing == false)
        return;

    if (mType == "Dot")
    {
        mPoints.Add(new PointF(e.X, e.Y)); 
        mImgGraph.DrawLines(mPen, mPoints.ToArray());
        mPoints.Clear();
    }
    else if (mType == "Line")
    {
        mImgGraph.DrawLine(mPen, mLastPoint, new PointF(e.X, e.Y));
    }
    mIsDrawing = false;

    pictureBox_draw.Image = mDrawedImg; //已经画好的会面作为当前画板的背景
}


©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页