This is the code I use to draw rectangles from the RichTexbox text:
try
{
pictureBox1.Image = null;
bm = new Bitmap(OrgPic.Width, OrgPic.Height);
//Location
string spli1 = ScriptBox.Text; var p = spli1.Split('(', ')')[1];
string spli2 = (p.ToString().Split(',', ',')[1]);
string source = spli2;
string loc_1 = string.Concat(source.Where(c => !char.IsWhiteSpace(c)));
string[] coords = loc_1.Split('.');
Point lp = new Point(int.Parse(coords[0]), int.Parse(coords[1])); ;
Console_.Text += $"This Lines {ScriptBox.LinesCount}";
Console_.Text += "\n" + "split1: " + spli1.ToString();
Console_.Text += "\n" + "split2: " + loc_1.ToString();
Console_.Text += "\n" + "cords: " + coords.ToString();
Console_.Text += "\n" + "lp_Point: " + lp.ToString();
//Color
string color = ScriptBox.Text; var r = Color.FromName(color.Split('(', ',')[1]);
string colors = (r.ToString().Split('.', ']')[1]);
Console_.Text += "\n" + "Color final:" + colors.ToString();
Console_.Text += "\n" + "Color Sin split:" + r.ToString();
Color f = Color.FromName(colors);
Pen pen = new Pen(f);
pen.Width = 4;
gF = Graphics.FromImage(bm);
gF.DrawRectangle(pen, lp.X, lp.Y, 100, 60);
pictureBox1.Image = bm;
}
catch (Exception)
{
}
I basically search for the word Rect.Draw followed by the color. [selected color] and the coordinates in which to place the rectangle. The problem is that when I go through the entire RichTexbox for the functions, it only draws the rectangle once, I don't know if I can explain myself. Example
Code 1:
Rect.Draw (color.red, 90.5)
this draws the red rectangle in its respective position
Code 2:
Rect.Draw (color.red, 90.5)
Rect.Draw (color.green, 100.5)
the code 2 it does not draw two rectangles. only respect the first and if i delete the first, the second being the only one will have priority.
Apparent solution: I would like to know how I can read RichTexbox line by line and treat each line as separate text. thus draw each rectangle procedurally.
First, RichTextBox has a string[] Lines
property that you can use.
Also, this seems like a case basically begging to use regular expression (regex). Going by your code and the use of string magic you probably haven't heard of it before but regex is used for parsing strings and extracting information based on patterns. That is to say, pretty much exactly what you're trying to do here.
using System.Text.RegularExpressions;
partial class Form1 : Form
{
Regex rectRegex = null;
private void ProcessRtf()
{
//init regex once.
if(rectRegex == null)
rectRegex = new Regex("Rect\.Draw\s*\(color\.(?<COL>[A-Za-z]+),\s+(?<POS>\d+(\.\d+)?)\)");
foreach(string line in ScriptBox.Lines)
{
//for example: line = "Rect.Draw(color.red, 90.5)"
var match = rectRegex.Match(line);
if(match.Success)
{
string col = match.Groups["COL"].Value; //col = "red"
string pos = match.Groups["POS"].Value; //pos = "90.5"
//draw your rectangle
break; //abort foreach loop.
}
}
}
}