gpt4 book ai didi

c# - 在 C# 中用鼠标画线的正确方法是什么

转载 作者:太空狗 更新时间:2023-10-29 18:30:12 26 4
gpt4 key购买 nike

这是我用鼠标在图表上绘制自定义线条的绘图代码。你能帮我正确地做吗?

namespace Grafi
{
public partial class Form1 : Form
{

bool isDrawing = false;
Point prevPoint;

public Form1()
{
InitializeComponent();
}

private void chartTemperature_MouseDown(object sender, MouseEventArgs e)
{
isDrawing = true;
prevPoint = e.Location;
}

private void chartTemperature_MouseMove(object sender, MouseEventArgs e)
{
Pen p = new Pen(Color.Red, 2);
if (isDrawing)
{
Graphics g = chartTemperature.CreateGraphics();
g.DrawLine(p, prevPoint, e.Location);
prevPoint = e.Location;

numOfMouseEvents = 0;
}
p.Dispose();
}

private void chartTemperature_MouseUp(object sender, MouseEventArgs e)
{
isDrawing = false;
}
}
}

问题是,当我调整表格大小时,我的线条消失了。只要引发 onPaint 事件,它就会消失。

最佳答案

试试这个... 这是一种笔画绘制方法,实现起来非常简单,并且尽可能接近您自己的代码。 Stokes 是鼠标移动的单独集合。鼠标在向下和向上之间的每次移动都被记录为一个笔划,所有的笔划都被收集起来,然后在触发 paint 事件时重新绘制。这个例子很简单,但可以作为一个很好的起点。

请注意,您必须为图表对象添加绘制处理程序。

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

namespace Grafi
{
public partial class Form1 : Form
{
bool isDrawing;
// our collection of strokes for drawing
List<List<Point>> _strokes = new List<List<Point>>();
// the current stroke being drawn
List<Point> _currStroke;
// our pen
Pen _pen = new Pen(Color.Red, 2);

public Form1()
{
InitializeComponent();
}

private void chartTemperature_MouseDown(object sender, MouseEventArgs e)
{
isDrawing = true;
// mouse is down, starting new stroke
_currStroke = new List<Point>();
// add the initial point to the new stroke
_currStroke.Add(e.Location);
// add the new stroke collection to our strokes collection
_strokes.Add(_currStroke);
}

private void chartTemperature_MouseMove(object sender, MouseEventArgs e)
{
if (isDrawing)
{
// record stroke point if we're in drawing mode
_currStroke.Add(e.Location);
Refresh(); // refresh the drawing to see the latest section
}
}

private void chartTemperature_MouseUp(object sender, MouseEventArgs e)
{
isDrawing = false;
}

private void chartTemperature_Paint(object sender, PaintEventArgs e)
{
// now handle and redraw our strokes on the paint event
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
foreach (List<Point> stroke in _strokes.Where(x => x.Count > 1))
e.Graphics.DrawLines(_pen, stroke.ToArray());
}
}
}

关于c# - 在 C# 中用鼠标画线的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4164864/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com