WindowsFormsApplication1.Form1.Dispose(bool)':no suitable method found to override - c#

For an assignment I've had to convert a fractal rendering program from Java to C# and I think I've done it but when i try to run it I get the error that is present in the title and I have no idea why it is happening. This is the code for the renderer itself which presents me with no errors:
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 Form1
{
public partial class Form1 : Form
{
public Form1()
{
init();
start();
this.DoubleBuffered = true;
}
//code to convert HSB to RGB from HSB.cs. All your code so i made it take up less space.
public struct HSBColor
{
float h;
float s;
float b;
int a;
public HSBColor(float h, float s, float b) { this.a = 0xff; this.h = Math.Min(Math.Max(h, 0), 255); this.s = Math.Min(Math.Max(s, 0), 255); this.b = Math.Min(Math.Max(b, 0), 255); }
public HSBColor(int a, float h, float s, float b) { this.a = a; this.h = Math.Min(Math.Max(h, 0), 255); this.s = Math.Min(Math.Max(s, 0), 255); this.b = Math.Min(Math.Max(b, 0), 255); }
public float H { get { return h; } }
public float S { get { return s; } }
public float B { get { return b; } }
public int A { get { return a; } }
public Color Color { get { return FromHSB(this); } }
public static Color FromHSB(HSBColor hsbColor)
{
float r = hsbColor.b;
float g = hsbColor.b;
float b = hsbColor.b;
if (hsbColor.s != 0)
{
float max = hsbColor.b; float dif = hsbColor.b * hsbColor.s / 255f; float min = hsbColor.b - dif; float h = hsbColor.h * 360f / 255f;
if (h < 60f) { r = max; g = h * dif / 60f + min; b = min; }
else if (h < 120f) { r = -(h - 120f) * dif / 60f + min; g = max; b = min; }
else if (h < 180f) { r = min; g = max; b = (h - 120f) * dif / 60f + min; }
else if (h < 240f) { r = min; g = -(h - 240f) * dif / 60f + min; b = max; }
else if (h < 300f) { r = (h - 240f) * dif / 60f + min; g = min; b = max; }
else if (h <= 360f) { r = max; g = min; b = -(h - 360f) * dif / 60 + min; }
else { r = 0; g = 0; b = 0; }
}
return Color.FromArgb(hsbColor.a, (int)Math.Round(Math.Min(Math.Max(r, 0), 255)), (int)Math.Round(Math.Min(Math.Max(g, 0), 255)), (int)Math.Round(Math.Min(Math.Max(b, 0), 255)));
}
}
private const int MAX = 256; // max iterations
private const double SX = -2.025; // start value real
private const double SY = -1.125; // start value imaginary
private const double EX = 0.6; // end value real
private const double EY = 1.125; // end value imaginary
private static int x1, y1, xs, ys, xe, ye;
private static double xstart, ystart, xende, yende, xzoom, yzoom;
private static float xy;
private int c = 0;
//private Image picture; Taken out, not needed
// create rectangle variable JGB
Rectangle rec;
private Graphics g1;
//private Cursor c1, c2; Taken out, not needed
private System.Drawing.Bitmap bitmap;
public void init()
{
//setSize(640, 480); changed this code to JGB:
this.Size = new Size(640, 480);
// Taken all lines out below. Not needed.
/*finished = false;
addMouseListener(this);
addMouseMotionListener(this);
c1 = new Cursor(Cursor.WAIT_CURSOR);
c2 = new Cursor(Cursor.CROSSHAIR_CURSOR); */
x1 = 640;
y1 = 480;
xy = (float)x1 / (float)y1;
//picture = createImage(x1, y1); Taken out and replaced with JGB:
bitmap = new Bitmap(x1, y1);
//g1 = picture.getGraphics(); changed to get my bitmap
g1 = Graphics.FromImage(bitmap);
//finished = true; Finished variable deleted so not needed
}
//Code below didnt appear to do anything so i deleted it
/*public void destroy() // delete all instances
{
if (finished)
{
removeMouseListener(this);
removeMouseMotionListener(this);
picture = null;
g1 = null;
c1 = null;
c2 = null;
System.gc(); // garbage collection
}
} */
public void start()
{
//action = false;
//rectangle = false;
initvalues();
// added dialog box for instance loading and save varaibles needed for position and zoom to text file
DialogResult dialog = MessageBox.Show("Would You Like to Load Your Last Instance?", "Load Instance?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (dialog == DialogResult.Yes)
{
string[] lines = System.IO.File.ReadAllLines(#"C:\Users\Public\Writelines.txt");
xzoom = System.Convert.ToDouble(lines[0]);
yzoom = System.Convert.ToDouble(lines[1]);
xstart = System.Convert.ToDouble(lines[2]);
ystart = System.Convert.ToDouble(lines[3]);
}
else
{
xzoom = (xende - xstart) / (double)x1;
yzoom = (yende - ystart) / (double)y1;
}
mandelbrot();
}
public void stop()
{
}
/*public void paint(Graphics g, PaintEventArgs e)
{
update(g);
}
public void update(Graphics g)
{
//g.DrawImage(picture, 0, 0);
}*/
private void mandelbrot()
{
int x, y;
float h, b, alt = 0.0f;
Color color;
Pen pen = new Pen(Color.Black);
for (x = 0; x < x1; x += 2)
for (y = 0; y < y1; y++)
{
h = pointcolour(xstart + xzoom * (double)x, ystart + yzoom * (double)y, c);
if (h != alt)
{
b = 1.0f - h * h;
color = HSBColor.FromHSB(new HSBColor(h * 255, 0.8f * 255, b * 255));
pen = new Pen(color);
alt = h;
}
g1.DrawLine(pen, x, y, x + 1, y);
}
}
private float pointcolour(double xwert, double ywert, int j)
{
double r = 0.0, i = 0.0, m = 0.0;
// int j = 0;
while ((j < MAX) && (m < 4.0))
{
j++;
m = r * r - i * i;
i = 2.0 * r * i + ywert;
r = m + xwert;
}
return (float)j / (float)MAX;
}
private void initvalues()
{
xstart = SX;
ystart = SY;
xende = EX;
yende = EY;
if ((float)((xende - xstart) / (yende - ystart)) != xy)
xstart = xende - (yende - ystart) * (double)xy;
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g1 = e.Graphics;
g1.DrawImage(bitmap, 0, 0, x1, y1);
using (Pen pen = new Pen(Color.White, 2))
{
e.Graphics.DrawRectangle(pen, rec);
}
Invalidate();
}
//added load method
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
xe = e.X;
ye = e.Y;
if (xs < xe)
{
if (ys < ye) rec = new Rectangle(xs, ys, (xe - xs), (ye - ys));
else rec = new Rectangle(xs, ye, (xe - xs), (ys - ye));
}
else
{
if (ys < ye) rec = new Rectangle(xe, ys, (xs - xe), (ye - ys));
else rec = new Rectangle(xe, ye, (xs - xe), (ys - ye));
}
this.Invalidate();
}
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
// e.consume();
xs = e.X;
ys = e.Y; // starting point y
this.Invalidate();
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
rec = new Rectangle(0, 0, 0, 0);
if (e.Button == MouseButtons.Left)
{
int z, w;
//e.consume();
//xe = e.X;
//ye = e.Y;
if (xs > xe)
{
z = xs;
xs = xe;
xe = z;
}
if (ys > ye)
{
z = ys;
ys = ye;
ye = z;
}
w = (xe - xs);
z = (ye - ys);
if ((w < 2) && (z < 2)) initvalues();
else
{
if (((float)w > (float)z * xy)) ye = (int)((float)ys + (float)w / xy);
else xe = (int)((float)xs + (float)z * xy);
xende = xstart + xzoom * (double)xe;
yende = ystart + yzoom * (double)ye;
xstart += xzoom * (double)xs;
ystart += yzoom * (double)ys;
}
xzoom = (xende - xstart) / (double)x1;
yzoom = (yende - ystart) / (double)y1;
mandelbrot();
string stringxzoom = xzoom.ToString();
string stringyzoom = yzoom.ToString();
string stringystart = ystart.ToString();
string stringxstart = xstart.ToString();
string[] lines = { stringxzoom, stringyzoom, stringxstart, stringystart };
System.IO.File.WriteAllLines(#"C:\Users\Public\Writelines.txt", lines);
this.Invalidate();
//Repaint();
}
}
private void restartToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Restart();
}
private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void menuToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
}
}
and this is the code that is used for the form designer which was auto generated and I'm not sure why an error is being presented because I've never had one before:
namespace WindowsFormsApplication1
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Text = "Form1";
}
#endregion
}
}

I believe it is caused because your namespaces are not the same. Since the partial code generated by the designer doesn't inherit from Form, you don't have a method to override. Once you make the two classes tie together properly by matching the namespaces, it should work.
To fix it, you can either change the namespace of the designer code to match your namespace of Form1:
namespace Form1
{
partial class Form1
{
//...
}
}
Or change your form to match the designer:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
//....
}
}

Edit the project properties and update the Default namespace to match the desired namespace for all forms

Related

I want to implement a maze game function that prevents players from moving when they encounter a wall

bluepicturebox = PlayerPictureBox
NewgameButton = btnCreate
First, the shape of the maze was implemented in gdi+.
How do I implement the function of the player moving, but if I encounter a wall, how do I implement the function of not moving?
private void btnCreate_Click(object sender, EventArgs e)
{
int wid = 15;
int hgt = 15;
CellWidth = picMaze.ClientSize.Width / (wid+2);
CellHeight = picMaze.ClientSize.Height / (hgt+2);
Xmin = (picMaze.ClientSize.Width - wid * CellWidth) / 2;
Ymin = (picMaze.ClientSize.Height - hgt * CellHeight) / 2;
MazeNode[,] nodes = MakeNodes(wid, hgt);
MakeRandomMaze(nodes[0, 0]);
DisplayMaze(nodes);
PlayerPictureBox.Visible = true;
arrivePicturBox.Visible = true;
PlayerPictureBox.Location = new Point(70,51);
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
switch (keyData)
{
case Keys.Left:
PlayerPictureBox.Left -= 5;
break;
case Keys.Right:
PlayerPictureBox.Left += 5;
break;
case Keys.Up:
PlayerPictureBox.Top -= 5;
break;
case Keys.Down:
PlayerPictureBox.Top += 5;
break;
default: return base.ProcessCmdKey(ref msg, keyData);
}
return true;
}
You need to implement a collision algorithm between a rectangle (in your case, it is a square) and a line segment. Even though all the shapes are axis-aligned, the algorithm is pretty complex. It involves a lot of vector math and computational geometry tricks. I don't think that you may want to learn the math behind it. Therefore, I don't explain the algorithm. If you want, you can ask another question about how it works.
The implementation is my own implementation. It is not based on any paper on the subject or external example source code. It may not be optimized well. Keep that in mind.
I have created a LineSegment class to hold the line information and if you would use my algorithm, I suggest you to use the class or extend it according to your needs.
PS: I must admit that I supposed that the collision algorithm would be simple but it has evolved a far complex algorithm especially, for a beginner to the collision math.
Here is the example Winforms App. You can tinker it as you want.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace LineRectangleCollision
{
public partial class Form1 : Form
{
public Form1()
{
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint, true);
InitializeComponent();
lineSegments = new List<LineSegment>();
lineSegments.Add(new LineSegment(new PointF(100, 100), new PointF(200, 100)));
lineSegments.Add(new LineSegment(new PointF(100, 100), new PointF(100, 300)));
lineSegments.Add(new LineSegment(new PointF(400, 100), new PointF(400, 300)));
points = new List<PointF>();
points.Add(new PointF(10, 10));
points.Add(new PointF(256, 485));
points.Add(new PointF(110, 50));
rectangle = new RectangleF(0, 0, 30, 30);
}
private List<LineSegment> lineSegments;
private List<PointF> points;
private RectangleF rectangle;
private float velocity = 5f;
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics g = e.Graphics;
g.Clear(Color.White);
for (int i = 0; i < points.Count; i++)
g.FillEllipse(Brushes.Blue, points[i].X - 2, points[i].Y - 2, 4, 4);
for (int i = 0; i < lineSegments.Count; i++)
lineSegments[i].Draw(g);
g.FillRectangle(Brushes.Red, rectangle);
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
switch (e.KeyCode)
{
case Keys.Left:
rectangle.Offset(-velocity, 0);
break;
case Keys.Up:
rectangle.Offset(0, -velocity);
break;
case Keys.Right:
rectangle.Offset(velocity, 0);
break;
case Keys.Down:
rectangle.Offset(0, velocity);
break;
}
bool result = false;
for (int i = 0; i < lineSegments.Count; i++)
{
PointF translationVector = CheckCollision(rectangle, lineSegments[i], out result);
if (result)
{
rectangle.Offset(translationVector.X, translationVector.Y);
continue;
}
}
for (int i = 0; i < points.Count; i++)
{
PointF translationVector = CheckCollision(rectangle, points[i], out result);
if (result)
{
rectangle.Offset(translationVector.X, translationVector.Y);
continue;
}
}
Invalidate();
}
private PointF CheckCollision(RectangleF rect, LineSegment line, out bool result)
{
PointF lineParallel = line.Unit;
PointF rectCenter = new PointF(rect.X + rect.Width / 2.0f, rect.Y + rect.Height / 2.0f);
PointF collisionVector = VectorMath.Subtract(rectCenter, line.Start);
float minHalfLength = line.IsVertical ? rect.Width : rect.Height;
minHalfLength /= 2.0f;
float length = VectorMath.Length(VectorMath.Subtract(line.End, line.Start))
float t = VectorMath.Dot(collisionVector, lineParallel);
t = t < 0 ? t + minHalfLength : t - minHalfLength;
if (t > 0 && t <= length)
{
PointF translationVector = CheckCollision(rect, line.Start, out result);
if (result)
return translationVector;
translationVector = CheckCollision(rect, line.End, out result);
if (result)
return translationVector;
PointF collisionNormal = VectorMath.RightPerp(lineParallel);
float d = VectorMath.Dot(collisionNormal, collisionVector);
if (d < 0)
collisionNormal = new PointF(-collisionNormal.X, -collisionNormal.Y);
d = Math.Abs(d);
if (d > minHalfLength)
{
result = false;
return PointF.Empty;
}
result = true;
float penetration = minHalfLength - d + 0.5f;
return new PointF(penetration * collisionNormal.X, penetration * collisionNormal.Y);
}
result = false;
return PointF.Empty;
}
private PointF CheckCollision(RectangleF rect, PointF point, out bool result)
{
if(rect.Contains(point))
{
LineSegment[] sides = new LineSegment[4];
sides[0] = new LineSegment(rect.X, rect.Y, rect.X + rect.Width, rect.Y);
sides[1] = new LineSegment(rect.X + rect.Width, rect.Y, rect.X + rect.Width, rect.Y + rect.Height);
sides[2] = new LineSegment(rect.X + rect.Width, rect.Y + rect.Height, rect.X, rect.Y + rect.Height);
sides[3] = new LineSegment(rect.X, rect.Y + rect.Height, rect.X, rect.Y);
result = true;
float minPen = float.MaxValue;
int index = 0;
for (int i = 0; i < 4; i++)
{
float d = VectorMath.GetDistanceBetweenPointLine(point, sides[i]);
if (d < minPen)
{
minPen = d;
index = i;
}
}
return VectorMath.Multiply(VectorMath.RightPerp(sides[index].Unit), minPen);
}
result = false;
return PointF.Empty;
}
private class LineSegment
{
public PointF Start;
public PointF End;
public LineSegment(float x0, float y0, float x1, float y1) : this(new PointF(x0, y0), new PointF(x1, y1))
{
}
public LineSegment(PointF start, PointF end)
{
Start = start;
End = end;
}
public bool IsVertical
{
get
{
return Start.X == End.X;
}
}
public PointF Unit
{
get
{
PointF unit = new PointF(End.X - Start.X, End.Y - Start.Y);
float length = VectorMath.Length(unit);
unit.X /= length;
unit.Y /= length;
return unit;
}
}
public void Draw(Graphics g)
{
using (Pen pen = new Pen(Color.Black, 2.0f))
g.DrawLine(pen, Start, End);
}
}
private class VectorMath
{
public static float Dot(PointF v0, PointF v1)
{
return v0.X * v1.X + v0.Y * v1.Y;
}
public static float Length(PointF vector)
{
return (float)Math.Sqrt(vector.X * vector.X + vector.Y * vector.Y);
}
public static PointF LeftPerp(PointF vector)
{
return new PointF(vector.Y, vector.X);
}
public static PointF RightPerp(PointF vector)
{
return new PointF(-vector.Y, vector.X);
}
public static PointF Add(PointF v0, PointF v1)
{
return new PointF(v0.X + v1.X, v0.Y + v1.Y);
}
public static PointF Subtract(PointF v0, PointF v1)
{
return new PointF(v0.X - v1.X, v0.Y - v1.Y);
}
public static PointF Multiply(PointF vector, float scaler)
{
return new PointF(vector.X * scaler, vector.Y * scaler);
}
public static PointF Negate(PointF vector)
{
return Multiply(vector, -1.0f);
}
public static float GetDistanceBetweenPointLine(PointF point, LineSegment line)
{
PointF unitParallel = line.Unit;
PointF normal = RightPerp(unitParallel);
float d = Dot(normal, Subtract(point, line.Start));
return Math.Abs(d);
}
}
}
}

How to draw a rainbow line using Graphic class c#

So i'm trying to create infinite rainbow line. Here ColorUtils class How do I get a rainbow color gradient in C#? (I'm using Framework 4.7.3
int rainbowStage = 0;
int rainbowNext = 0;
private void Form1_Paint(object sender, PaintEventArgs e)
{
BackgroundWorker worker = new BackgroundWorker();
PointF point1 = new PointF(100.0F, 100.0F);
PointF point2 = new PointF(235.0F, 100.0F);
worker.DoWork += async delegate (object s, DoWorkEventArgs args)
{
do
{
Console.WriteLine(await getRainbow());
rainbowNext++;
Pen pen = new Pen(await getRainbow(), 3);
e.Graphics.DrawLine(pen, point1, point2);
e.Graphics.Clear(Color.FromArgb(26, 26, 26));
} while (rainbowStage == rainbowNext);
};
worker.RunWorkerCompleted += delegate (object s, RunWorkerCompletedEventArgs args)
{
rainbowStage++;
};
}
async Task<ColorUtils.ColorRGB> getRainbow()
{
for (double i = 0; i < 1; i += 0.01)
{
ColorUtils.ColorRGB c = ColorUtils.HSL2RGB(i, 0.5, 0.5);
return c;
}
ColorUtils.ColorRGB c1 = ColorUtils.HSL2RGB(0, 0.5, 0.5);
return c1;
}
So, you have found how to generate a sequence of rainbow colors. But your code is not actually correct, it should be something like:
IEnumerable<Color> GetRainbow()
{
for (double i = 0; i < 1; i += 0.1)
{
Color c = ColorUtils.HSL2RGB(i, 0.5, 0.5);
yield return c;
}
}
That will give you a sequence of ten colors, using the actual color type used by winforms.
To draw the rainbow we need to draw each color as a separate line, slightly offset from each other. To get the offset we need to do some vector math:
var dir = point1 - point2;
var offset= new PointF(dir.Y, -dir.X).Normalize();
...
public static PointF Normalize(this PointF A)
{
float distance = Math.Sqrt(A.X * A.X + A.Y * A.Y);
return new PointF(A.X / distance, A.Y / distance);
}
public static PointF Mul(this PointF a, float b)
{
return new PointF(a.X * b, a.Y * b);
}
We can then begin drawing our line:
var colors = GetRainbow().ToList();
var width = 10f / colors.Count;
for(int i = 0; i < colors.Count; i++){
using var pen = new Pen(colors[i], width);
var o = offset.Mul( width * i)
e.Graphics.DrawLine(pen, point1 + o, point2 + o);
}
That should give you a rainbow line of with 10 with one pixel per color, adjust the width literal to get a wider line.
An alternative approach would be to create something like a texture brush displaying the rainbow and use that for drawing.
Note that all drawing code need to be run on the UI thread, and any other calculations are really fast, they just involve a handful of simple math operations. So there is nothing at all to be gained from trying to run anything on any background thread.
Here's a copy, paste, run, version of what you're trying to do:
public class Form1 : Form
{
public Form1()
{
this.Paint += Form1_Paint;
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
foreach (var rgb in GetRainbow().Select((colour, indexer) => (colour, indexer)))
{
Console.WriteLine(rgb.colour);
using (Pen pen = new Pen(rgb.colour, 3))
{
e.Graphics.DrawLine(pen, new PointF(100.0F, 100.0F + rgb.indexer), new PointF(235.0F, 100.0F + rgb.indexer));
}
}
}
IEnumerable<ColorRGB> GetRainbow()
{
for (double i = 0; i < 1; i += 0.01)
{
yield return HSL2RGB(i, 0.5, 0.5);
}
}
public struct ColorRGB
{
public byte R;
public byte G;
public byte B;
public ColorRGB(Color value)
{
this.R = value.R;
this.G = value.G;
this.B = value.B;
}
public static implicit operator Color(ColorRGB rgb)
{
Color c = Color.FromArgb(rgb.R, rgb.G, rgb.B);
return c;
}
public static explicit operator ColorRGB(Color c)
{
return new ColorRGB(c);
}
}
public static ColorRGB HSL2RGB(double h, double sl, double l)
{
double v;
double r, g, b;
r = l; // default to gray
g = l;
b = l;
v = (l <= 0.5) ? (l * (1.0 + sl)) : (l + sl - l * sl);
if (v > 0)
{
double m;
double sv;
int sextant;
double fract, vsf, mid1, mid2;
m = l + l - v;
sv = (v - m) / v;
h *= 6.0;
sextant = (int)h;
fract = h - sextant;
vsf = v * sv * fract;
mid1 = m + vsf;
mid2 = v - vsf;
switch (sextant)
{
case 0:
r = v;
g = mid1;
b = m;
break;
case 1:
r = mid2;
g = v;
b = m;
break;
case 2:
r = m;
g = v;
b = mid1;
break;
case 3:
r = m;
g = mid2;
b = v;
break;
case 4:
r = mid1;
g = m;
b = v;
break;
case 5:
r = v;
g = m;
b = mid2;
break;
}
}
ColorRGB rgb;
rgb.R = Convert.ToByte(r * 255.0f);
rgb.G = Convert.ToByte(g * 255.0f);
rgb.B = Convert.ToByte(b * 255.0f);
return rgb;
}
}
When run, I get this:
There were too many things going wrong with your original code, but don't use async/await, don't forget to dispose disposables, don't forget to compute the actual line you're trying to draw, use yield return to get your rainbow colours, etc.

How to solve the Fatal Execution Engine Error in OpenTK?

I am trying to develop a program using OpenTK. The purpose of this program is to load a STL (stereolithography) file in ASCII format, then render it in OpenTK, and keep track of the selected object using name stack. In this program, I use the mouse right click to get the selected object.
The brief explanation of STL file is here:
https://en.wikipedia.org/wiki/STL_(file_format)
In my code, I am using 2 STL files. The first STL file is a simple geometry (file size 8 kb). The second STL file is a complex geometry (file size 1167 kb). When I used the first STL file and run my code, it just worked fine when I use my mouse right click function.
However, when I used second STL file and run my code (follow by mouse right click), I got this Fatal Execution Engine Error Exception. I am not sure why I get this error. Is it because of the file size is too big? But I can render this second file into OpenTK. Is it because I have to set a large enough buff size here to avoid this exception?
Do you have any idea why this is happening? Is there any method to avoid this error/exception?
The link for these two STL files are here:
https://drive.google.com/drive/folders/1v9bUzqVx1a1_KbnSXCQ5LREoQaAFUn2D?usp=sharing
Here are my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenTK;
using OpenTK.Graphics.OpenGL;
using OpenTK.Input;
namespace OpenTK3D
{
public class Game3D
{
private GameWindow window;
private float zoom;
private bool hasRotationStarted;
private int startX;
private int startY;
private float xRotAngle;
private float yRotAngle;
private bool hasPanningStarted;
private float xTrans;
private float yTrans;
private int BUFSIZE = 512;
private string filePath = #"C:\Users\mpelmt\Desktop\ISF forming direction optimization\verify_65_40_yForming_noFlange.STL";
private double angleLimit = 60;
public Game3D(GameWindow wd)
{
this.window = wd;
var zBoundary = zBoundaryValue(filePath);
hasRotationStarted = false;
startX = 0;
startY = 0;
xRotAngle = 28;
yRotAngle = -45;
zoom = -(float)zBoundary;
hasPanningStarted = false;
xTrans = 0;
yTrans = 0;
start();
}
public void start()
{
window.Load += loaded;
window.Resize += resize;
window.RenderFrame += renderFrame;
window.MouseDown += mouseLeftPress;
window.MouseUp += mouseRelease;
window.MouseMove += mouseDragEvent;
window.MouseWheel += MouseWheelHandler;
window.MouseDown += wheelPressEvent;
window.MouseUp += wheelReleaseEvent;
window.MouseMove += wheelDragEvent;
window.MouseDown += select;
window.Run(1.0 / 60.0);
}
private List<double> getAllSTLData(string path)
{
string[] text = System.IO.File.ReadAllLines(path);
List<double> allData = new List<double>();
foreach (var line in text)
{
if (line.Contains("facet normal"))
{
var normal = Array.ConvertAll(line.Remove(0, 16).Split(' '), double.Parse);
allData.AddRange(normal);
}
if (line.Contains("vertex"))
{
var position = Array.ConvertAll(line.Remove(0, 16).Split(' '), double.Parse);
allData.AddRange(position);
}
}
return allData;
}
private Dictionary<int, List<double>> getAllFacets(string path)
{
var allSTLData = getAllSTLData(path);
var allFacet = new Dictionary<int, List<double>>();
for (int i = 0; i < (allSTLData.Count) / 12; i++)
{
allFacet.Add(i + 1, allSTLData.GetRange(12 * i, 12));
}
return allFacet;
}
private double yBoundaryValue(string path)
{
var allFacets = getAllFacets(path);
var listOfY = new List<double>();
foreach (KeyValuePair<int, List<double>> kp in allFacets)
{
var vertex = kp.Value.GetRange(3, 9);
listOfY.Add(vertex[1]);
listOfY.Add(vertex[4]);
listOfY.Add(vertex[7]);
}
return listOfY.Max() - listOfY.Min();
}
private double xBoundaryValue(string path)
{
var allFacets = getAllFacets(path);
var listOfX = new List<double>();
foreach (KeyValuePair<int, List<double>> kp in allFacets)
{
var vertex = kp.Value.GetRange(3, 9);
listOfX.Add(vertex[0]);
listOfX.Add(vertex[3]);
listOfX.Add(vertex[6]);
}
return listOfX.Max() - listOfX.Min();
}
private double zBoundaryValue(string path)
{
var allFacets = getAllFacets(path);
var listOfZ = new List<double>();
foreach (KeyValuePair<int, List<double>> kp in allFacets)
{
var vertex = kp.Value.GetRange(3, 9);
listOfZ.Add(vertex[2]);
listOfZ.Add(vertex[5]);
listOfZ.Add(vertex[8]);
}
return listOfZ.Max() - listOfZ.Min();
}
private List<double> getAngleRangeWithinLimit(double angleLimit)
{
var result = new List<double>();
var section = (int)angleLimit / 5;
var remain = angleLimit % 5;
for (int i = 0; i < section; i++)
{
result.Add(5 * i);
result.Add(5 * i + 5);
}
if (remain != 0)
{
result.Add(result.Last());
result.Add(result.Last() + remain);
}
return result;
}
public Dictionary<int, List<double>> pickSelectFacetsByAngleInYForm(string path, double angleLimit)
{
var result = new Dictionary<int, List<double>>();
var allFacets = getAllFacets(path);
var angleRange = getAngleRangeWithinLimit(angleLimit);
foreach (KeyValuePair<int, List<double>> kp in allFacets)
{
var data = kp.Value;
var id = kp.Key;
var tempList = new List<double>();
var angle = Math.Acos(Math.Abs(data[1])) * 180 / (Math.PI);
for (int i = 0; i < angleRange.Count / 2; i++)
{
if (angle >= angleLimit)
{
tempList.AddRange(data);
tempList.Add(angleLimit + 1);
break;
}
else if (angle >= angleRange[2 * i] && angle <= angleRange[2 * i + 1])
{
tempList.AddRange(data);
tempList.Add(angleRange[2 * i + 1]);
break;
}
}
result.Add(id, tempList);
}
return result;
}
public void renderColorPlotYForm(string path, double angleLimit)
{
var plotData = pickSelectFacetsByAngleInYForm(path, angleLimit);
foreach (KeyValuePair<int, List<double>> kv in plotData)
{
var id = kv.Key;
var data = kv.Value;
GL.Begin(BeginMode.Triangles);
var colorRange = data.Last();
if (colorRange == 5)
{
// green
GL.Color3(0.0, 1.0, 0.0);
}
if (colorRange == angleLimit + 1)
{
//red
GL.Color3(1.0, 0.0, 0.0);
}
if (colorRange == 30)
{
// yellow
GL.Color3(1.0, 1.0, 0.0);
}
if (colorRange < 30 && colorRange > 5)
{
var diff = 30 - colorRange;
var ratio = diff / 25;
GL.Color3(1 - ratio, 1, 0);
}
if (colorRange > 30 && colorRange < angleLimit + 1)
{
var ratio = (angleLimit - colorRange) / angleLimit;
GL.Color3(1, 1 - ratio, 0);
}
var listOfVertex = data.GetRange(3, 9);
for (int i = 0; i < 3; i++)
{
var vertex = listOfVertex.GetRange(3 * i, 3);
GL.Vertex3(vertex[0], vertex[1], vertex[2]);
}
GL.End();
}
}
public void pickSelectColorPlotYForm(string path, double angleLimit)
{
var plotData = pickSelectFacetsByAngleInYForm(path, angleLimit);
foreach (KeyValuePair<int, List<double>> kv in plotData)
{
var id = kv.Key;
var data = kv.Value;
GL.LoadName(id);
GL.Begin(BeginMode.Triangles);
var colorRange = data.Last();
if (colorRange == 5)
{
// green
GL.Color3(0.0, 1.0, 0.0);
}
if (colorRange == angleLimit + 1)
{
//red
GL.Color3(1.0, 0.0, 0.0);
}
if (colorRange == 30)
{
// yellow
GL.Color3(1.0, 1.0, 0.0);
}
if (colorRange < 30 && colorRange > 5)
{
var diff = 30 - colorRange;
var ratio = diff / 25;
GL.Color3(1 - ratio, 1, 0);
}
if (colorRange > 30 && colorRange < angleLimit + 1)
{
var ratio = (angleLimit - colorRange) / angleLimit;
GL.Color3(1, 1 - ratio, 0);
}
var listOfVertex = data.GetRange(3, 9);
for (int i = 0; i < 3; i++)
{
var vertex = listOfVertex.GetRange(3 * i, 3);
GL.Vertex3(vertex[0], vertex[1], vertex[2]);
}
GL.End();
}
}
public void loaded(object o, EventArgs e)
{
GL.ClearColor(0.0f, 0.0f, 0.0f, 0.0f);
GL.Enable(EnableCap.DepthTest);
}
public void renderFrame(object o, EventArgs e)
{
var xBoundary = xBoundaryValue(filePath);
var yBoundary = yBoundaryValue(filePath);
var zBoundary = zBoundaryValue(filePath);
var xCen = xBoundary / 2;
var yCen = yBoundary / 2;
var zCen = zBoundary / 2;
GL.LoadIdentity();
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
GL.Translate(xTrans, yTrans, zoom*3);
GL.Rotate(xRotAngle, 1.0, 0, 0);
GL.Rotate(yRotAngle, 0, 1, 0);
renderColorPlotYForm(filePath, angleLimit);
window.SwapBuffers();
}
public void resize(object o, EventArgs e)
{
var zBoundary = zBoundaryValue(filePath);
GL.Viewport(0, 0, window.Width, window.Height);
GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
// the fov must be radian
var matrix = Matrix4.CreatePerspectiveFieldOfView(45.0f*(MathHelper.Pi)/180, window.Width / window.Height, 1.0f, (float)zBoundary * (float)zBoundary);
GL.LoadMatrix(ref matrix);
GL.MatrixMode(MatrixMode.Modelview);
}
private void processHits(int hits, int[] buffer)
{
Console.WriteLine("hit: {0}", hits);
if (hits > 0)
{
int choose = buffer[3];
int depth = buffer[1];
for (int i = 0; i < hits; i++)
{
if (buffer[i * 4 + 1] < depth)
{
choose = buffer[i * 4 + 3];
depth = buffer[i * 4 + 1];
}
}
Console.WriteLine("choosen: {0}", choose);
}
}
private void GluPickMatrix(double x, double y, double deltax, double deltay, int[] viewport)
{
if (deltax <= 0 || deltay <= 0)
{
return;
}
GL.Translate((viewport[2] - 2 * (x - viewport[0])) / deltax, (viewport[3] - 2 * (y - viewport[1])) / deltay, 0);
GL.Scale(viewport[2] / deltax, viewport[3] / deltay, 1.0);
}
public void select(object o, MouseEventArgs e)
{
var zBoundary = zBoundaryValue(filePath);
var mouse = Mouse.GetState();
if (mouse[MouseButton.Right])
{
var buffer = new int[BUFSIZE];
var viewPort = new int[4];
int hits;
GL.GetInteger(GetPName.Viewport, viewPort);
GL.SelectBuffer(BUFSIZE, buffer);
GL.RenderMode(RenderingMode.Select);
GL.InitNames();
GL.PushName(0);
GL.MatrixMode(MatrixMode.Projection);
GL.PushMatrix();
GL.LoadIdentity();
GluPickMatrix(e.Mouse.X, viewPort[3] - e.Mouse.Y, 5.0, 5.0, viewPort);
var matrix = Matrix4.CreatePerspectiveFieldOfView(45.0f * (MathHelper.Pi) / 180, window.Width / window.Height, 1.0f, (float)zBoundary * (float)zBoundary);
GL.MultMatrix(ref matrix);
GL.MatrixMode(MatrixMode.Modelview);
pickSelectColorPlotYForm(filePath, angleLimit);
GL.MatrixMode(MatrixMode.Projection);
GL.PopMatrix();
GL.MatrixMode(MatrixMode.Modelview);
GL.Flush();
hits = GL.RenderMode(RenderingMode.Render);
processHits(hits, buffer);
}
}
public void mouseLeftPress(object sender, MouseEventArgs e)
{
if (e.Mouse.LeftButton == ButtonState.Pressed)
{
hasRotationStarted = true;
startX = e.Mouse.X;
startY = e.Mouse.Y;
}
}
public void mouseRelease(object sender, MouseEventArgs e)
{
if (e.Mouse.LeftButton == ButtonState.Released)
{
hasRotationStarted = false;
}
}
public void mouseDragEvent(object sender, MouseEventArgs e)
{
if (hasRotationStarted == true && e.Mouse.X != e.Mouse.Y)
{
xRotAngle = xRotAngle + (e.Mouse.Y - startY);
yRotAngle = yRotAngle + (e.Mouse.X - startX);
startX = e.Mouse.X;
startY = e.Mouse.Y;
}
}
public void MouseWheelHandler(object sender, MouseWheelEventArgs e)
{
var xBoundary = xBoundaryValue(filePath);
if (e.Delta > 0)
{
zoom += 0.1f * (float)xBoundary;
}
if (e.Delta < 0)
{
zoom -= 0.1f * (float)xBoundary;
}
}
public void wheelPressEvent(object sender, MouseEventArgs e)
{
if (e.Mouse.MiddleButton == ButtonState.Pressed)
{
hasPanningStarted = true;
startX = e.Mouse.X;
startY = e.Mouse.Y;
}
}
public void wheelReleaseEvent(object sender, MouseEventArgs e)
{
if (e.Mouse.MiddleButton == ButtonState.Released)
{
hasPanningStarted = false;
}
}
public void wheelDragEvent(object sender, MouseEventArgs e)
{
if (hasPanningStarted == true)
{
xTrans = xTrans + 2 * (e.Mouse.X - startX);
yTrans = yTrans - 2 * (e.Mouse.Y - startY);
startX = e.Mouse.X;
startY = e.Mouse.Y;
}
}
}
}
Here is the main function:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenTK;
namespace OpenTK3D
{
class Program
{
static void Main(string[] args)
{
var window = new GameWindow(500, 500);
var gm = new Game3D(window);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Press enter to finish...");
Console.ReadLine();
}
}
}
This is the result when I run my code using the first STL file (it works fine):
When I run my code using the second STL file, I got this Fatal Execution Engine Error:

Fractal renderer not displaying image at all?

I'm converting a fractal renderer from Java to C# for an assignment and I think I have everything set up but the fractal itself won't render.
This is a photo of when I run the program:
And here is how my files are laid out in the folder that contains the project itself:
This is the code that I am using for the actually rendering itself which I think has no errors but if I've missed something extremely obvious then I'm sorry for wasting all of your time:
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
init();
start();
this.DoubleBuffered = true;
}
//code to convert HSB to RGB from HSB.cs. All your code so i made it take up less space.
public struct HSBColor
{
float h;
float s;
float b;
int a;
public HSBColor(float h, float s, float b) { this.a = 0xff; this.h = Math.Min(Math.Max(h, 0), 255); this.s = Math.Min(Math.Max(s, 0), 255); this.b = Math.Min(Math.Max(b, 0), 255); }
public HSBColor(int a, float h, float s, float b) { this.a = a; this.h = Math.Min(Math.Max(h, 0), 255); this.s = Math.Min(Math.Max(s, 0), 255); this.b = Math.Min(Math.Max(b, 0), 255); }
public float H { get { return h; } }
public float S { get { return s; } }
public float B { get { return b; } }
public int A { get { return a; } }
public Color Color { get { return FromHSB(this); } }
public static Color FromHSB(HSBColor hsbColor)
{
float r = hsbColor.b;
float g = hsbColor.b;
float b = hsbColor.b;
if (hsbColor.s != 0)
{
float max = hsbColor.b; float dif = hsbColor.b * hsbColor.s / 255f; float min = hsbColor.b - dif; float h = hsbColor.h * 360f / 255f;
if (h < 60f) { r = max; g = h * dif / 60f + min; b = min; }
else if (h < 120f) { r = -(h - 120f) * dif / 60f + min; g = max; b = min; }
else if (h < 180f) { r = min; g = max; b = (h - 120f) * dif / 60f + min; }
else if (h < 240f) { r = min; g = -(h - 240f) * dif / 60f + min; b = max; }
else if (h < 300f) { r = (h - 240f) * dif / 60f + min; g = min; b = max; }
else if (h <= 360f) { r = max; g = min; b = -(h - 360f) * dif / 60 + min; }
else { r = 0; g = 0; b = 0; }
}
return Color.FromArgb(hsbColor.a, (int)Math.Round(Math.Min(Math.Max(r, 0), 255)), (int)Math.Round(Math.Min(Math.Max(g, 0), 255)), (int)Math.Round(Math.Min(Math.Max(b, 0), 255)));
}
}
private const int MAX = 256; // max iterations
private const double SX = -2.025; // start value real
private const double SY = -1.125; // start value imaginary
private const double EX = 0.6; // end value real
private const double EY = 1.125; // end value imaginary
private static int x1, y1, xs, ys, xe, ye;
private static double xstart, ystart, xende, yende, xzoom, yzoom;
private static float xy;
private int c = 0;
//private Image picture; Taken out, not needed
// create rectangle variable JGB
Rectangle rec;
private Graphics g1;
//private Cursor c1, c2; Taken out, not needed
private System.Drawing.Bitmap bitmap;
public void init()
{
//setSize(640, 480); changed this code to JGB:
this.Size = new Size(640, 480);
// Taken all lines out below. Not needed.
/*finished = false;
addMouseListener(this);
addMouseMotionListener(this);
c1 = new Cursor(Cursor.WAIT_CURSOR);
c2 = new Cursor(Cursor.CROSSHAIR_CURSOR); */
x1 = 640;
y1 = 480;
xy = (float)x1 / (float)y1;
//picture = createImage(x1, y1); Taken out and replaced with JGB:
bitmap = new Bitmap(x1, y1);
//g1 = picture.getGraphics(); changed to get my bitmap
g1 = Graphics.FromImage(bitmap);
//finished = true; Finished variable deleted so not needed
}
//Code below didnt appear to do anything so i deleted it
/*public void destroy() // delete all instances
{
if (finished)
{
removeMouseListener(this);
removeMouseMotionListener(this);
picture = null;
g1 = null;
c1 = null;
c2 = null;
System.gc(); // garbage collection
}
} */
public void start()
{
//action = false;
//rectangle = false;
initvalues();
// added dialog box for instance loading and save varaibles needed for position and zoom to text file
DialogResult dialog = MessageBox.Show("Would You Like to Load Your Last Instance?", "Load Instance?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (dialog == DialogResult.Yes)
{
string[] lines = System.IO.File.ReadAllLines(#"C:\Users\Public\Writelines.txt");
xzoom = System.Convert.ToDouble(lines[0]);
yzoom = System.Convert.ToDouble(lines[1]);
xstart = System.Convert.ToDouble(lines[2]);
ystart = System.Convert.ToDouble(lines[3]);
}
else
{
xzoom = (xende - xstart) / (double)x1;
yzoom = (yende - ystart) / (double)y1;
}
mandelbrot();
}
public void stop()
{
}
/*public void paint(Graphics g, PaintEventArgs e)
{
update(g);
}
public void update(Graphics g)
{
//g.DrawImage(picture, 0, 0);
}*/
private void mandelbrot()
{
int x, y;
float h, b, alt = 0.0f;
Color color;
Pen pen = new Pen(Color.Black);
for (x = 0; x < x1; x += 2)
for (y = 0; y < y1; y++)
{
h = pointcolour(xstart + xzoom * (double)x, ystart + yzoom * (double)y, c);
if (h != alt)
{
b = 1.0f - h * h;
color = HSBColor.FromHSB(new HSBColor(h * 255, 0.8f * 255, b * 255));
pen = new Pen(color);
alt = h;
}
g1.DrawLine(pen, x, y, x + 1, y);
}
}
private float pointcolour(double xwert, double ywert, int j)
{
double r = 0.0, i = 0.0, m = 0.0;
// int j = 0;
while ((j < MAX) && (m < 4.0))
{
j++;
m = r * r - i * i;
i = 2.0 * r * i + ywert;
r = m + xwert;
}
return (float)j / (float)MAX;
}
private void initvalues()
{
xstart = SX;
ystart = SY;
xende = EX;
yende = EY;
if ((float)((xende - xstart) / (yende - ystart)) != xy)
xstart = xende - (yende - ystart) * (double)xy;
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g1 = e.Graphics;
g1.DrawImage(bitmap, 0, 0, x1, y1);
using (Pen pen = new Pen(Color.White, 2))
{
e.Graphics.DrawRectangle(pen, rec);
}
Invalidate();
}
//added load method
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
xe = e.X;
ye = e.Y;
if (xs < xe)
{
if (ys < ye) rec = new Rectangle(xs, ys, (xe - xs), (ye - ys));
else rec = new Rectangle(xs, ye, (xe - xs), (ys - ye));
}
else
{
if (ys < ye) rec = new Rectangle(xe, ys, (xs - xe), (ye - ys));
else rec = new Rectangle(xe, ye, (xs - xe), (ys - ye));
}
this.Invalidate();
}
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
// e.consume();
xs = e.X;
ys = e.Y; // starting point y
this.Invalidate();
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
rec = new Rectangle(0, 0, 0, 0);
if (e.Button == MouseButtons.Left)
{
int z, w;
//e.consume();
//xe = e.X;
//ye = e.Y;
if (xs > xe)
{
z = xs;
xs = xe;
xe = z;
}
if (ys > ye)
{
z = ys;
ys = ye;
ye = z;
}
w = (xe - xs);
z = (ye - ys);
if ((w < 2) && (z < 2)) initvalues();
else
{
if (((float)w > (float)z * xy)) ye = (int)((float)ys + (float)w / xy);
else xe = (int)((float)xs + (float)z * xy);
xende = xstart + xzoom * (double)xe;
yende = ystart + yzoom * (double)ye;
xstart += xzoom * (double)xs;
ystart += yzoom * (double)ys;
}
xzoom = (xende - xstart) / (double)x1;
yzoom = (yende - ystart) / (double)y1;
mandelbrot();
string stringxzoom = xzoom.ToString();
string stringyzoom = yzoom.ToString();
string stringystart = ystart.ToString();
string stringxstart = xstart.ToString();
string[] lines = { stringxzoom, stringyzoom, stringxstart, stringystart };
System.IO.File.WriteAllLines(#"C:\Users\Public\Writelines.txt", lines);
this.Invalidate();
//Repaint();
}
}
private void restartToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Restart();
}
private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void menuToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
}
}
Change your Form1() code into these
InitializeComponent();
init();
start();
this.DoubleBuffered = true;
this.pictureBox1.Image = bitmap;
You took out the InitializeComponent call (which should be automatically generated) and you never set the resulting bitmap as the image of the pictureBox. Also, you might wanna set the picturebox Size mode to Zoom and enlarge it.

passing mouse clicks to line algorithm

I wrote bresenham algorithm for
0<Angular coefficient<1
I don't know much about graphics in C#,I realized that for drawing pixles I can use the function Fillrectangel with coordinate 1,1
I wanted to write my code then when clicking the mouse on panel and in two positions draw me a line from x0,y0 to xEnd,yEnd
so here is my code which has exception
Null reference exception was unhandled
object reference not set to an instance of the object
this exception is in line e.Graphics.FillRectangle(new SolidBrush(grad1), x, y, 1, 1);
I think the problem is that object e is Null and I should new it but how?
How can I correct my code so as to draw Line?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
Line l=new Line();
l.LineBres(Cursor.Position.X, Cursor.Position.Y, Cursor.Position.X, Cursor.Position.Y);
}
}
}
public class Line
{
System.Windows.Forms.DrawItemEventArgs e;
Color grad1 = Color.FromArgb(165, 194, 245);
public void LineBres(int x0, int y0, int xEnd, int yEnd)
{
int dx = xEnd - x0;
int dy = yEnd = y0;
int p = 2 * dy - dx;
int twoDy = 2 * dy;
int twoDyMinusDx = 2 * (dy - dx);
int x, y;
if (x0 > xEnd)
{
x = xEnd;
y = yEnd;
xEnd = x0;
}
else
{
x = x0;
y = y0;
}
e.Graphics.FillRectangle(new SolidBrush(grad1), x, y, 1, 1);
while (x < xEnd)
{
x++;
if (p < 0)
p += twoDy;
else
{
y++;
p += twoDyMinusDx;
}
e.Graphics.FillRectangle(new SolidBrush(grad1), x, y, 1, 1);
}
}
}
Here is what you need to change:
Add mouse click event for panel and change your Line code a bit - remove System.Windows.Forms.DrawItemEventArgs e; and pass Graphics of panel with panel1.CreateGraphics();. Here is the code:
private int firstX, firstY;//store coordinates of first click
private bool firstClick = true;
private void panel1_MouseClick(object sender, MouseEventArgs e)
{
if (firstClick)
{
firstX = e.X;
firstY = e.Y;
firstClick = false;
}
else
{
Line l = new Line();
l.LineBres(firstX, firstY, e.X, e.Y, panel1.CreateGraphics());
firstClick = true;
}
}
public class Line
{
private Color grad1 = Color.FromArgb(165, 194, 245);
public void LineBres(int x0, int y0, int xEnd, int yEnd, Graphics e)
{
int dx = xEnd - x0;
int dy = yEnd = y0;
int p = 2*dy - dx;
int twoDy = 2*dy;
int twoDyMinusDx = 2*(dy - dx);
int x, y;
if (x0 > xEnd)
{
x = xEnd;
y = yEnd;
xEnd = x0;
}
else
{
x = x0;
y = y0;
}
e.FillRectangle(new SolidBrush(grad1), x, y, 1, 1);
while (x < xEnd)
{
x++;
if (p < 0)
p += twoDy;
else
{
y++;
p += twoDyMinusDx;
}
e.FillRectangle(new SolidBrush(grad1), x, y, 1, 1);
}
}
}

Categories

Resources