问题
I can not figure out if there is there any way in GDI32 to draw a string on two not adjacent areas (let's say Rectangles) on a form?.
The text should automatically split if the edge of the first rectangle is reached as shown in the example picture. Thanks for your help.
回答1:
An example, using two Labels
and a TrackBar
.
The TrackBar
determines a string position inside one Label, which reflects on the second Label each time the string is moved.
This cascading effect is generated using the .Invalidate() method of the second Label, which is called from the first label Paint() event.
I'm just using Graphics.MeasureString() and Graphics.DrawString() here.
You could also use the related TextRenderer methods, but in a Label the measures are the same.
A visual representaton of the result:
float stringLength = 0F;
string loremIpsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
StringFormat MarqueeFormat = new StringFormat(StringFormatFlags.NoWrap | StringFormatFlags.FitBlackBox)
{
Alignment = StringAlignment.Near,
Trimming = StringTrimming.None
};
private void lblMarquee1_Paint(object sender, PaintEventArgs e)
{
SizeF stringSize = e.Graphics.MeasureString(loremIpsum, ((Control)sender).Font, -1, MarqueeFormat);
PointF stringLocation = new PointF(trackBar1.Value, (((Control)sender).Height - stringSize.Height) / 2);
stringLength = ((Control)sender).ClientRectangle.Width - stringLocation.X;
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
e.Graphics.DrawString(loremIpsum, ((Control)sender).Font, Brushes.Black, stringLocation, MarqueeFormat);
lblMarquee2.Invalidate();
}
private void lblMarquee2_Paint(object sender, PaintEventArgs e)
{
SizeF stringSize = e.Graphics.MeasureString(loremIpsum, ((Control)sender).Font, -1, MarqueeFormat);
PointF stringLocation = new PointF(-stringLength, (((Control)sender).Height - stringSize.Height) / 2);
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
e.Graphics.DrawString(loremIpsum, ((Control)sender).Font, Brushes.Black, stringLocation, MarqueeFormat);
}
private void trackBar1_ValueChanged(object sender, EventArgs e)
{
lblMarquee1.Invalidate();
}
来源:https://stackoverflow.com/questions/51928757/how-to-draw-a-string-on-two-not-adjacent-areas