相对于文本框中的文本块垂直居中控制

时间:2014-12-26 17:06:48

标签: c# position controls centering

我有一个带有一些html元素的文本框,每个元素都显示为一个单独的文本块。现在我想添加一些图片框,每个元素一个,垂直居中于相应元素的左边(在嵌套元素的情况下,例如示例中div内的p,div应该优先,p应该被忽略)

到目前为止,我提出的代码显然缺少某些东西,因为Y坐标不正确。请参见下图,其中两个黑色斑点代表两个图片框:

enter image description here

以下是代码:

string str = textBox1.Text;
string pattern = "<(?<tag>div|p|h[1-6])>";
Regex r = new Regex(pattern);
Match m = r.Match(str);
int i = 1;
while (m.Success) {
    string new_s = str.Substring(m.Index + 3);
    string new_p = "</" + m.Groups["tag"].Value + ">";
    Match m_end = Regex.Match(new_s, new_p);
    if (m_end.Success) { // Corresponding end tag exists
        Point start_p = textBox1.GetPositionFromCharIndex(m.Index);
        Point end_p = textBox1.GetPositionFromCharIndex(m_end.Index);
        double top = start_p.Y;
        double bottom = end_p.Y;
        int midpoint = (int)(top + bottom) / 2;
        PictureBox pictureBox = new PictureBox();
        pictureBox.Name = "pictureBox" + i.ToString();
        pictureBox.Location = new System.Drawing.Point(15, midpoint + 7);
        pictureBox.Image = Image.FromFile("c:\\blob.png");
        pictureBox.Size = new Size(15, 15);
        pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
        this.Controls.Add(pictureBox);
        m_end.Index.ToString());
    }
    i++;
    m = r.Match(str, m_end.Index);
}

我还尝试将textBox1.Font.Size添加到等式中,但这并没有帮助。并且线高很难,因为每个块在技术上是一条线。有关如何进行的任何建议吗?

编辑:由于Point基于左上角,因此使用Font.Size来查找底部似乎是合理的。这似乎为第一个blob提供了正确的位置。

1 个答案:

答案 0 :(得分:0)

我想我找到了解决方案。基本上,由于每次搜索新标签时缩短输入字符串,如果我不添加从搜索字符串中删除的字符数,则结束标记位置会出错。或者在代码中,希望有点清楚:

while (m.Success) {
    string new_s = str.Substring(m.Index);
    string new_p = "</" + m.Groups["tag"].Value + ">";
    Match m_end = Regex.Match(new_s, new_p);
    Point start_p = textBox1.GetPositionFromCharIndex(m.Index);
    Point end_p = textBox1.GetPositionFromCharIndex(m_end.Index + m.Index);
    int top = (int)start_p.Y;
    int bottom = (int)(end_p.Y + textBox1.Font.Size);
    if (m_end.Success) {
        int midpoint = (top + bottom) / 2;
        PictureBox pictureBox = new PictureBox();
        pictureBox.Name = "pictureBox" + i.ToString();
        pictureBox.Location = new System.Drawing.Point(15, midpoint + 7 + 2);
        pictureBox.Image = Image.FromFile("c:\\blob.png");
        pictureBox.Size = new Size(15, 15);
        pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
        this.Controls.Add(pictureBox);
    }
    i++;
    m = r.Match(str, m_end.Index + m.Index);
}