在运行时绘制椭圆并使用拓宽方法
本文关键字:方法 运行时 绘制 | 更新日期: 2023-09-27 18:07:36
**我使用以下代码在运行时绘制椭圆。在代码中,我使用图形路径绘图(实际上这是项目要求),并使用拓宽方法的图形路径。但是它给出了运行时异常"内存不足"。我可以在椭圆的情况下使用这个方法吗?
在运行时绘制矩形的情况下,使用width方法可以正常工作。
请解决这个问题并给我一些建议。* *
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
Rectangle r;
bool isDown = false;
int initialX;
int initialY;
bool IsDrowing =true;
GraphicsPath gp1;
GraphicsPath gp2;
GraphicsPath gp3;
GraphicsPath gp;
Graphics g;
bool contained;
bool containedE;
bool containedC;
private void Form2_MouseDown(object sender, MouseEventArgs e)
{
isDown = true;
IsDrowing = true;
initialX = e.X;
initialY = e.Y;
}
private void Form2_MouseMove(object sender, MouseEventArgs e)
{
//IsDrowing = true;
if (isDown == true)
{
int width = e.X - initialX, height = e.Y - initialY;
r = new Rectangle(Math.Min(e.X, initialX),
Math.Min(e.Y, initialY),
Math.Abs(e.X - initialX),
Math.Abs(e.Y - initialY));
this.Invalidate();
}
}
private void Form2_Paint(object sender, PaintEventArgs e)
{
g = this.CreateGraphics();
gp = new GraphicsPath();
Pen pen = new Pen(Color.Red);
gp.AddEllipse(r);
gp.Widen(pen);
pen.DashStyle = DashStyle.Dash;
if (IsDrowing)
{
g.DrawPath(pen, gp);
}
private void Form2_MouseUp(object sender, MouseEventArgs e)
{
IsDrowing = false;
this.Refresh();
}
}
基本上:避免使用GraphicsPath。扩大的方法。它有bug,搜索"spirograph bug"
在您的例子中,这是因为您试图加宽一个0 × 0的矩形。像这样修改你的代码:
private void Form2_Paint(object sender, PaintEventArgs e)
{
if (IsDrowing)
{
g = e.Graphics;
gp = new GraphicsPath();
gp.AddEllipse(r);
gp.Widen(new Pen(Color.Red, 10));
Pen pen = new Pen(Color.Red, 1);
pen.DashStyle = DashStyle.Dash;
g.DrawPath(pen, gp);
}
}
这可能需要额外的工作,但是避免扩大一个空的矩形/椭圆