C# 拉绳互相重叠?

C# 拉绳互相重叠?,c#,graphics,drawstring,C#,Graphics,Drawstring,法典: 法典B: Image imageChipsetName = new System.Drawing.Bitmap(photoWidth, photoHeight); StringFormat strFormat = new StringFormat(); strFormat.Alignment = StringAlignment.Center; strFormat.LineAlignment = StringAlignment.Center; Graphics graphics = G

法典:

法典B:

Image imageChipsetName = new System.Drawing.Bitmap(photoWidth, photoHeight);

StringFormat strFormat = new StringFormat();
strFormat.Alignment = StringAlignment.Center;
strFormat.LineAlignment = StringAlignment.Center;

Graphics graphics = Graphics.FromImage(imageChipsetName);
graphics.DrawString(stringA + "\n",
                    new Font("Tahoma", 14, FontStyle.Underline), Brushes.Black,
                    new RectangleF(0, 0, photoWidth, photoHeight), strFormat);
graphics.DrawString( stringB,
                    new Font("Tahoma", 14), Brushes.Black,
                    new RectangleF(0, 0, photoWidth, photoHeight), strFormat);
我需要在一个盒子里画两条线。StringA具有下划线样式,而StringB不具有下划线样式


CodeB几乎实现了我想要的,但是
stringA
stringB
共享相同的风格。所以我用CodeA进行了测试,但是使用它的程序是两个字符串相互重叠。我可以知道吗

代码A的问题是,stringA和stringB都是在完全相同的位置绘制的

graphics.DrawString
将字符串转换为图像并打印在纸上。 字符串转换为图像后,“\n”没有任何意义。它不会被打印,也不会创建新的行。事实上,纸上没有“线”。只是图像

你需要给stringB不同的位置。使用
Graphics.MeasureString(String,Font)
测量stringA的大小,然后根据结果调整stringB的位置

Image imageChipsetName = new System.Drawing.Bitmap(photoWidth, photoHeight);

StringFormat strFormat = new StringFormat();
strFormat.Alignment = StringAlignment.Center;
strFormat.LineAlignment = StringAlignment.Center;

Graphics graphics = Graphics.FromImage(imageChipsetName);
graphics.DrawString(stringA + "\n"+stringB,
                    new Font("Tahoma", 14, FontStyle.Underline), Brushes.Black,
                    new RectangleF(0, 0, photoWidth, photoHeight), strFormat);
DrawString()
只在一次调用中处理换行符。它从一个调用到下一个调用不携带状态。因此,如果需要在多行上使用不同的样式绘制,则需要为每次调用
DrawString()
指定正确绘制字符串的位置。有关详细信息和其他信息的链接,请参见标记的副本。
Image imageChipsetName = new System.Drawing.Bitmap(photoWidth, photoHeight);

StringFormat strFormat = new StringFormat();
strFormat.Alignment = StringAlignment.Center;
strFormat.LineAlignment = StringAlignment.Center;
Font strFontA = new Font("Tahoma", 14, FontStyle.Underline);//Font used by stringA


Graphics graphics = Graphics.FromImage(imageChipsetName);
graphics.DrawString(stringA + "\n",
                    strFont_A, Brushes.Black,
                    new RectangleF(0, 0, photoWidth, photoHeight), strFormat);

SizeF stringSizeA = new SizeF();
stringSizeA = Graphics.MeasureString(stringA, strFont_A);//Measuring the size of stringA

graphics.DrawString(stringB,
                    new Font("Tahoma", 14), Brushes.Black,
                    new RectangleF(0, stringSizeA.Height, photoWidth, photoHeight - stringSizeA.Height), strFormat);