我一直在使用C#进行绘画应用;我想添加一个选项,用当前画笔切换绘制椭圆。我一直难以理解如何制作它,以便在按住鼠标的同时椭圆的大小和Y位置发生变化。有任何想法吗? 这是我的代码。
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;
namespace ZSPainter
{
public partial class Form1 : Form
{
string drawToolString;
Graphics g;
bool c = false;
bool drawEllipse = false;
Point sp = new Point(0, 0);
Point ep = new Point(0, 0);
Pen p = new Pen(Color.Black, 1);
Brush b = new SolidBrush(Color.Black);
public Form1()
{
InitializeComponent();
}
private void penToolStripMenuItem_Click(object sender, EventArgs e)
{
drawToolString = "pen";
toolString.Text = "Current Tool: Pen";
}
private void brushToolStripMenuItem_Click(object sender, EventArgs e)
{
drawToolString = "brush";
toolString.Text = "Current Tool: Brush";
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
sp = e.Location;
if(e.Button == MouseButtons.Left)
c = true;
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (drawToolString == "pen" && c)
{
ep = e.Location;
g = this.CreateGraphics();
if(!drawEllipse)
g.DrawLine(p, sp, ep);
/*else
*
*------Here is where I want an ellipse to drawn if drawEllipse is true.------
*/
}
else if (drawToolString == "brush" && c)
{
ep = e.Location;
g = this.CreateGraphics();
if(!drawEllipse)
g.DrawLine(new Pen(b, 3), sp, ep);
/*else
*
*------Here is where I want an ellipse to drawn if drawEllipse is true.------
*/
}
sp = ep;
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
c = false;
}
private void ellipse_Click(object sender, EventArgs e)
{
drawEllipse = !drawEllipse;
}
}
}
答案 0 :(得分:0)
使用具有透明背景的图片框,并且已从图像文件中绘制椭圆(每个示例)并将其放在鼠标坐标处。
但要注意,这会给你的代码带来很多麻烦,你正在绘制到表单,当它刷新时,所有内容都会在刷新的区域中被清除,所以如果你放置并移动一个控件,它就会被清除。
我建议创建一个Bitmap,将此位图设置为表单的背景并绘制到该位图,然后它将是持久的(并且也更容易保存)。
此外,您需要在MouseDown事件上设置鼠标捕获并在MouseUp上释放,否则表单在显示图片框后不会捕获MouseMove事件。
如果您不想使用图片框但是将绘图切换为位图,则可以在表格上绘画并刷新绘制椭圆的先前区域,这样绘图将被保留,椭圆会在它上面移动。