J'ai une ligne brisée (PointF[]
), certains string
et Graphics
objet. Maintenant, je veux dessiner cette chaîne sur ma ligne.Texte sur la ligne prédéfinie
Voici un exemple:
Y a-t-il des algorithmes pour le faire de la manière la plus facile?
[edit] Ok, j'ai essayé le code de @ endofzero et je l'ai modifié un peu. Voici la solution complète (avec des calculs d'angle et de distance):
private static void DrawBrokenString(Graphics g, IList<PointF> line, string text, Font font)
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.TextRenderingHint = TextRenderingHint.AntiAlias;
Pen pen = new Pen(Brushes.Black);
for (int index = 0; index < line.Count - 1; index++)
{
float distance = GetDistance(line[index], line[index + 1]);
if (text.Length > 0)
{
for (int cIndex = text.Length; cIndex >= 0; cIndex--)
{
SizeF textSize = g.MeasureString(text.Substring(0, cIndex).Trim(), font);
if (textSize.Width <= distance)
{
float rotation = GetAngle(line[index], line[index + 1]);
g.TranslateTransform(line[index].X, line[index].Y);
g.RotateTransform(rotation);
if (index != line.Count - 2)
{
g.DrawString(text.Substring(0, cIndex).Trim(), font, new SolidBrush(Color.Black),
new PointF(0, -textSize.Height));
}
else
{
g.DrawString(text.Trim(), font, new SolidBrush(Color.Black),
new PointF(0, -textSize.Height));
}
g.RotateTransform(-rotation);
g.TranslateTransform(-line[index].X, -line[index].Y);
text = text.Remove(0, cIndex);
break;
}
}
}
else
{
break;
}
g.DrawLine(pen, line[index].X, line[index].Y, line[index + 1].X, line[index + 1].Y);
}
}
private static float GetDistance(PointF p1, PointF p2)
{
return (float) Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2));
}
private static float GetAngle(PointF p1, PointF p2)
{
float c = (float) Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2));
if (c == 0)
return 0;
if (p1.X > p2.X)
return (float) (Math.Asin((p1.Y - p2.Y)/c)*180/Math.PI - 180);
return (float) (Math.Asin((p2.Y - p1.Y)/c)*180/Math.PI);
}
Maintenant je dois la seule chose à finir mon problème. Je ne veux pas que les chaînes se chevauchent. Des idées? Ahhh, et quand nous ne pouvons pas tirer une chaîne sur le chemin (en raison du montant trop de pauses, il doit être établi au-dessus de la ligne (en haut au milieu)
est ici l'exemple de chevauchement indésirable.
a été la chaîne d'entrée « Certains texte sur la ligne » ou [ « Une partie du texte », « sur la ligne »]? –
Je récupère la chaîne entière, alors « Une partie du texte sur la ligne »: SI doivent scinder moi – Nickon
Vous pouvez dessiner le texte pivotée à l'aide DrawString après une RotateTransform appropriée (plus ici: http://msdn.microsoft.com/en -us/bibliothèque/a0z3f662 (v = VS.100) .aspx) et on peut voir la largeur d'une chaîne en utilisant la méthode de MeasureString (http://msdn.microsoft.com/en-us/library/system.drawing. graphics.measurestring (v = vs.100) .aspx). Cela peut vous aider à diviser le texte – BlackBear