Form1.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Drawing.Imaging;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Windows.Forms;
  11. using System.IO;
  12. // This is the code for your desktop app.
  13. // Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app.
  14. namespace SketchAssistant
  15. {
  16. public partial class Form1 : Form
  17. {
  18. public Form1()
  19. {
  20. InitializeComponent();
  21. }
  22. /**********************************/
  23. /*** CLASS VARIABLES START HERE ***/
  24. /**********************************/
  25. //Different Program States
  26. public enum ProgramState
  27. {
  28. Idle,
  29. Draw,
  30. Delete
  31. }
  32. //Current Program State
  33. private ProgramState currentState;
  34. //Dialog to select a file.
  35. OpenFileDialog openFileDialogLeft = new OpenFileDialog();
  36. //Image loaded on the left
  37. Image leftImage = null;
  38. //Image on the right
  39. Image rightImage = null;
  40. //Current Line being Drawn
  41. List<Point> currentLine;
  42. //All Lines in the current session
  43. List<Tuple<bool,Line>> lineList = new List<Tuple<bool, Line>>();
  44. //Whether the Mouse is currently pressed in the rightPictureBox
  45. bool mousePressed = false;
  46. //The Position of the Cursor in the right picture box
  47. Point currentCursorPosition;
  48. //The Previous Cursor Position in the right picture box
  49. Point previousCursorPosition;
  50. //Queue for the cursorPositions
  51. Queue<Point> cursorPositions = new Queue<Point>();
  52. //The graphic representation of the right image
  53. Graphics graph = null;
  54. //Deletion Matrixes for checking postions of lines in the image
  55. bool[,] isFilledMatrix;
  56. HashSet<int>[,] linesMatrix;
  57. //Size of deletion area
  58. uint deletionSize = 2;
  59. //Dialog to save a file
  60. SaveFileDialog saveFileDialogRight = new SaveFileDialog();
  61. /******************************************/
  62. /*** FORM SPECIFIC FUNCTIONS START HERE ***/
  63. /******************************************/
  64. private void Form1_Load(object sender, EventArgs e)
  65. {
  66. currentState = ProgramState.Idle;
  67. this.DoubleBuffered = true;
  68. }
  69. //Resize Function connected to the form resize event, will refresh the form when it is resized
  70. private void Form1_Resize(object sender, System.EventArgs e)
  71. {
  72. this.Refresh();
  73. }
  74. //Load button, will open an OpenFileDialog
  75. private void loadToolStripMenuItem_Click(object sender, EventArgs e)
  76. {
  77. openFileDialogLeft.Filter = "Image (*.jpg, *.png, *.jpeg)|*.jpg;*.png;*.jpeg";
  78. if(openFileDialogLeft.ShowDialog() == DialogResult.OK)
  79. {
  80. toolStripLoadStatus.Text = openFileDialogLeft.SafeFileName;
  81. leftImage = Image.FromFile(openFileDialogLeft.FileName);
  82. pictureBoxLeft.Image = leftImage;
  83. //Refresh the left image box when the content is changed
  84. this.Refresh();
  85. }
  86. }
  87. //Save button, will open an SaveFileDialog
  88. private void saveToolStripMenuItem_Click(object sender, EventArgs e)
  89. {
  90. if (rightImage != null)
  91. {
  92. saveFileDialogRight.Filter = "Image|*.jpg;*.png;*.jpeg|" + "Vector Graphics (*svg|*.svg" + "All files (*.*)|*.*" ;
  93. ImageFormat format = ImageFormat.Jpeg;
  94. if (saveFileDialogRight.ShowDialog() == DialogResult.OK)
  95. {
  96. switch (saveFileDialogRight.Filter)
  97. {
  98. case ".svg":
  99. String returnString = createSvgTxt();
  100. File.WriteAllText(saveFileDialogRight.FileName, returnString);
  101. return;
  102. case ".png":
  103. format = ImageFormat.Png;
  104. break;
  105. case ".bmp":
  106. format = ImageFormat.Bmp;
  107. break;
  108. }
  109. pictureBoxRight.Image.Save(saveFileDialogRight.FileName, format);
  110. }
  111. }
  112. else
  113. {
  114. MessageBox.Show("The right picture box can't be empty");
  115. }
  116. }
  117. //Changes the state of the program to drawing
  118. private void drawButton_Click(object sender, EventArgs e)
  119. {
  120. if(rightImage != null)
  121. {
  122. if (currentState.Equals(ProgramState.Draw))
  123. {
  124. ChangeState(ProgramState.Idle);
  125. }
  126. else
  127. {
  128. ChangeState(ProgramState.Draw);
  129. }
  130. }
  131. }
  132. //Changes the state of the program to deletion
  133. private void deleteButton_Click(object sender, EventArgs e)
  134. {
  135. if (rightImage != null)
  136. {
  137. if (currentState.Equals(ProgramState.Delete))
  138. {
  139. ChangeState(ProgramState.Idle);
  140. }
  141. else
  142. {
  143. ChangeState(ProgramState.Delete);
  144. }
  145. }
  146. }
  147. //get current Mouse positon within the right picture box
  148. private void pictureBoxRight_MouseMove(object sender, MouseEventArgs e)
  149. {
  150. currentCursorPosition = ConvertCoordinates(new Point(e.X, e.Y));
  151. }
  152. //hold left mouse button to draw.
  153. private void pictureBoxRight_MouseDown(object sender, MouseEventArgs e)
  154. {
  155. mousePressed = true;
  156. if (currentState.Equals(ProgramState.Draw))
  157. {
  158. currentLine = new List<Point>();
  159. }
  160. }
  161. //when the picture box is clicked, add a point to the current line. Occurs f.ex. when using drawing tablets
  162. private void pictureBoxRight_Click(object sender, EventArgs e)
  163. {
  164. if (currentState.Equals(ProgramState.Draw))
  165. {
  166. List<Point> singlePoint = new List<Point> { currentCursorPosition };
  167. Line singlePointLine = new Line(singlePoint, lineList.Count);
  168. singlePointLine.PopulateMatrixes(isFilledMatrix, linesMatrix);
  169. singlePointLine.DrawLine(graph);
  170. pictureBoxRight.Image = rightImage;
  171. }
  172. }
  173. //Lift left mouse button to stop drawing and add a new Line.
  174. private void pictureBoxRight_MouseUp(object sender, MouseEventArgs e)
  175. {
  176. mousePressed = false;
  177. if (currentState.Equals(ProgramState.Draw) && currentLine.Count > 0)
  178. {
  179. Line newLine = new Line(currentLine, lineList.Count);
  180. lineList.Add(new Tuple<bool, Line>(true, newLine));
  181. newLine.PopulateMatrixes(isFilledMatrix, linesMatrix);
  182. }
  183. }
  184. //Button to create a new Canvas. Will create an empty image
  185. //which is the size of the left image, if there is one.
  186. //If there is no image loaded the canvas will be the size of the right picture box
  187. private void canvasButton_Click(object sender, EventArgs e)
  188. {
  189. DrawEmptyCanvas();
  190. //The following lines cannot be in DrawEmptyCanvas()
  191. isFilledMatrix = new bool[rightImage.Width, rightImage.Height];
  192. linesMatrix = new HashSet<int>[rightImage.Width, rightImage.Height];
  193. }
  194. //add a Point on every tick to the Drawpath
  195. private void mouseTimer_Tick(object sender, EventArgs e)
  196. {
  197. cursorPositions.Enqueue(currentCursorPosition);
  198. previousCursorPosition = cursorPositions.Dequeue();
  199. if (currentState.Equals(ProgramState.Draw) && mousePressed)
  200. {
  201. currentLine.Add(currentCursorPosition);
  202. Line drawline = new Line(currentLine);
  203. drawline.DrawLine(graph);
  204. pictureBoxRight.Image = rightImage;
  205. }
  206. if (currentState.Equals(ProgramState.Delete) && mousePressed)
  207. {
  208. List<Point> uncheckedPoints = Line.BresenhamLineAlgorithm(previousCursorPosition, currentCursorPosition);
  209. foreach (Point currPoint in uncheckedPoints)
  210. {
  211. HashSet<int> linesToDelete = CheckDeletionMatrixesAroundPoint(currPoint, deletionSize);
  212. if (linesToDelete.Count > 0)
  213. {
  214. foreach (int lineID in linesToDelete)
  215. {
  216. lineList[lineID] = new Tuple<bool, Line>(false, lineList[lineID].Item2);
  217. }
  218. RepopulateDeletionMatrixes();
  219. RedrawRightImage();
  220. }
  221. }
  222. }
  223. }
  224. /***********************************/
  225. /*** HELPER FUNCTIONS START HERE ***/
  226. /***********************************/
  227. /// <summary>
  228. /// Creates an empty Canvas
  229. /// </summary>
  230. private void DrawEmptyCanvas()
  231. {
  232. if (leftImage == null)
  233. {
  234. rightImage = new Bitmap(pictureBoxRight.Width, pictureBoxRight.Height);
  235. graph = Graphics.FromImage(rightImage);
  236. graph.FillRectangle(Brushes.White, 0, 0, pictureBoxRight.Width + 10, pictureBoxRight.Height + 10);
  237. pictureBoxRight.Image = rightImage;
  238. }
  239. else
  240. {
  241. rightImage = new Bitmap(leftImage.Width, leftImage.Height);
  242. graph = Graphics.FromImage(rightImage);
  243. graph.FillRectangle(Brushes.White, 0, 0, leftImage.Width + 10, leftImage.Height + 10);
  244. pictureBoxRight.Image = rightImage;
  245. }
  246. this.Refresh();
  247. pictureBoxRight.Refresh();
  248. }
  249. /// <summary>
  250. /// Redraws all lines in lineList, for which their associated boolean value equals true.
  251. /// </summary>
  252. private void RedrawRightImage()
  253. {
  254. DrawEmptyCanvas();
  255. foreach (Tuple<bool, Line> lineBoolTuple in lineList)
  256. {
  257. if (lineBoolTuple.Item1)
  258. {
  259. lineBoolTuple.Item2.DrawLine(graph);
  260. }
  261. }
  262. pictureBoxRight.Refresh();
  263. }
  264. /// <summary>
  265. /// A helper function which handles tasks associated witch changing states,
  266. /// such as checking and unchecking buttons and changing the state.
  267. /// </summary>
  268. /// <param name="newState">The new state of the program</param>
  269. private void ChangeState(ProgramState newState)
  270. {
  271. switch (currentState)
  272. {
  273. case ProgramState.Draw:
  274. drawButton.CheckState = CheckState.Unchecked;
  275. mouseTimer.Enabled = false;
  276. break;
  277. case ProgramState.Delete:
  278. deleteButton.CheckState = CheckState.Unchecked;
  279. mouseTimer.Enabled = false;
  280. break;
  281. default:
  282. break;
  283. }
  284. switch (newState)
  285. {
  286. case ProgramState.Draw:
  287. drawButton.CheckState = CheckState.Checked;
  288. mouseTimer.Enabled = true;
  289. break;
  290. case ProgramState.Delete:
  291. deleteButton.CheckState = CheckState.Checked;
  292. mouseTimer.Enabled = true;
  293. break;
  294. default:
  295. break;
  296. }
  297. currentState = newState;
  298. pictureBoxRight.Refresh();
  299. }
  300. /// <summary>
  301. /// A function that calculates the coordinates of a point on a zoomed in image.
  302. /// </summary>
  303. /// <param name="">The position of the mouse cursor</param>
  304. /// <returns>The real coordinates of the mouse cursor on the image</returns>
  305. private Point ConvertCoordinates(Point cursorPosition)
  306. {
  307. Point realCoordinates = new Point(5,3);
  308. if(pictureBoxRight.Image == null)
  309. {
  310. return cursorPosition;
  311. }
  312. int widthImage = pictureBoxRight.Image.Width;
  313. int heightImage = pictureBoxRight.Image.Height;
  314. int widthBox = pictureBoxRight.Width;
  315. int heightBox = pictureBoxRight.Height;
  316. float imageRatio = (float)widthImage / (float)heightImage;
  317. float containerRatio = (float)widthBox / (float)heightBox;
  318. if (imageRatio >= containerRatio)
  319. {
  320. //Image is wider than it is high
  321. float zoomFactor = (float)widthImage / (float)widthBox;
  322. float scaledHeight = heightImage / zoomFactor;
  323. float filler = (heightBox - scaledHeight) / 2;
  324. realCoordinates.X = (int)(cursorPosition.X * zoomFactor);
  325. realCoordinates.Y = (int)((cursorPosition.Y - filler) * zoomFactor);
  326. }
  327. else
  328. {
  329. //Image is higher than it is wide
  330. float zoomFactor = (float)heightImage / (float)heightBox;
  331. float scaledWidth = widthImage / zoomFactor;
  332. float filler = (widthBox - scaledWidth) / 2;
  333. realCoordinates.X = (int)((cursorPosition.X - filler) * zoomFactor);
  334. realCoordinates.Y = (int)(cursorPosition.Y * zoomFactor);
  335. }
  336. return realCoordinates;
  337. }
  338. /// <summary>
  339. /// A function that populates the matrixes needed for deletion detection with line data.
  340. /// </summary>
  341. private void RepopulateDeletionMatrixes()
  342. {
  343. if(rightImage != null)
  344. {
  345. isFilledMatrix = new bool[rightImage.Width,rightImage.Height];
  346. linesMatrix = new HashSet<int>[rightImage.Width, rightImage.Height];
  347. foreach(Tuple<bool,Line> lineTuple in lineList)
  348. {
  349. if (lineTuple.Item1)
  350. {
  351. lineTuple.Item2.PopulateMatrixes(isFilledMatrix, linesMatrix);
  352. }
  353. }
  354. }
  355. }
  356. /// <summary>
  357. /// A function that checks the deletion matrixes at a certain point
  358. /// and returns all Line ids at that point and in a square around it in a certain range.
  359. /// </summary>
  360. /// <param name="p">The point around which to check.</param>
  361. /// <param name="range">The range around the point. If range is 0, only the point is checked.</param>
  362. /// <returns>A List of all lines.</returns>
  363. private HashSet<int> CheckDeletionMatrixesAroundPoint(Point p, uint range)
  364. {
  365. HashSet<int> returnSet = new HashSet<int>();
  366. if (p.X >= 0 && p.Y >= 0 && p.X < rightImage.Width && p.Y < rightImage.Height)
  367. {
  368. if (isFilledMatrix[p.X, p.Y])
  369. {
  370. returnSet.UnionWith(linesMatrix[p.X, p.Y]);
  371. }
  372. }
  373. for (int x_mod = (int)range*(-1); x_mod < range; x_mod++)
  374. {
  375. for (int y_mod = (int)range * (-1); y_mod < range; y_mod++)
  376. {
  377. if (p.X + x_mod >= 0 && p.Y + y_mod >= 0 && p.X + x_mod < rightImage.Width && p.Y + y_mod < rightImage.Height)
  378. {
  379. if (isFilledMatrix[p.X + x_mod, p.Y + y_mod])
  380. {
  381. returnSet.UnionWith(linesMatrix[p.X + x_mod, p.Y + y_mod]);
  382. }
  383. }
  384. }
  385. }
  386. return returnSet;
  387. }
  388. private String createSvgTxt()
  389. {
  390. String newString = String.Format(@"< svg viewBox = ""0 0 {0} {1}"" xmlns = ""http://www.w3.org/2000/svg"" >", rightImage.Width, rightImage.Height);
  391. foreach (Tuple<bool,Line> lineTuple in lineList)
  392. {
  393. if(lineTuple.Item1 == true)
  394. {
  395. String nextLine = String.Format("\n" + @"<line x1 = ""{0}"" y1 = ""{1}""2 x2 = ""{2}"" y2 = ""{3}"" stroke = ""black"" />\n",
  396. lineTuple.Item2.GetStartPoint().X, lineTuple.Item2.GetStartPoint().Y, lineTuple.Item2.GetEndPoint().X, lineTuple.Item2.GetEndPoint().X);
  397. newString += nextLine;
  398. }
  399. }
  400. return newString;
  401. }
  402. private void saveToolStripMenuItem1_Click(object sender, EventArgs e)
  403. {
  404. }
  405. }
  406. }