問題描述
逐行讀取文本框並將其視為單獨的文本 (Read a textbox line by line and treat it as a separate text)
這是我用來從 RichTexbox 文本中繪製矩形的代碼:
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)
{
}
我基本上搜索單詞 Rect.Draw 後跟 顏色。[選定顏色] 以及放置矩形的坐標。問題是當我遍歷整個RichTexbox的功能時,它只繪製了一次矩形,我不知道我是否可以解釋自己。示例
代碼1:
Rect.Draw (color.red, 90.5)
這會在相應位置繪製紅色矩形
代碼2:
Rect.Draw (color.red, 90.5)
Rect.Draw (color.green, 100.5)
代碼2吧不繪製兩個矩形。只尊重第一個,如果我刪除第一個,則唯一的第二個將具有優先權。
明顯的解決方案:我想知道如何逐行閱讀 RichTexbox 並將每一行視為單獨的文本。因此按程序繪製每個矩形。
參考解法
方法 1:
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.
}
}
}
}
(by Moix、Jack T. Spades)