C# TextBox Line Spacing - c#

I'm working on a plugin for Paint.net that converts the current image to ASCII art. I have the conversion working fine, and it outputs the ASCII art into a TextBox control, with a fixed width font. My problem is, the ASCII art is stretched vertically, because of the line spacing in a TextBox. Is there any way to set the line spacing of a TextBox?

A TextBox simply shows single or multiline text with no formatting options - it can have a font but that applies to the TextBox and not to the text, so you can't have paragraph settings like line spacing as far as I know.
My first suggestion would be to use a RichTextBox, but then again, RTF doesn't have a code for line spacing so I believe that would be impossible as well.
So my final suggestions is to use an owner-drawn control. It shouldn't be too difficult with a fixed-width font - you know the location of each character is (x*w, y*h) where x and y are the character index and w and h are the size of one character.
Edit: Thinking about it a bit more, it's even simpler - simply separate the string to lines and draw each line.
Here's a simple control that does just that. When testing it I found that for Font = new Font(FontFamily.GenericMonospace, 10, FontStyle.Regular), the best value for Spacing was -9.
/// <summary>
/// Displays text allowing you to control the line spacing
/// </summary>
public class SpacedLabel : Control {
private string[] parts;
protected override void OnPaint(PaintEventArgs e) {
Graphics g = e.Graphics;
g.Clear(BackColor);
float lineHeight = g.MeasureString("X", Font).Height;
lineHeight += Spacing;
using (Brush brush = new SolidBrush(ForeColor)) {
for (int i = 0; i < parts.Length; i++) {
g.DrawString(parts[i], Font, brush, 0, i * lineHeight);
}
}
}
public override string Text {
get {
return base.Text;
}
set {
base.Text = value;
parts = (value ?? "").Replace("\r", "").Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
}
}
/// <summary>
/// Controls the change in spacing between lines.
/// </summary>
public float Spacing { get; set; }
}

Related

Adapt the height of a TextBox

I am working on a UserControl that contains a multiline TextBox.
When using my control, one will be able to set the text that will be displayed. The TextBox should then adapt its Height to make the text fit, the Width cannot change.
So here is the property that handles the text :
[Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))]
public string TextToDisplay
{
get
{
return internalTextBox.Text;
}
set
{
internalTextBox.Text = value;
AdaptTextBoxSize();
}
}
My first attempt was rather simple :
private void AdaptTextBoxSize()
{
int nbLignes = internalTextBox.Lines.Length;
float lineHeight = internalTextBox.Font.GetHeight();
internalTextBox.Height = (int)((nbLignes) * lineHeight);
}
This did not work as it doesn't take into account spacing between two lines of text. So the more lines I have in the text, the more I get clipped.
So I tried this :
private void AdaptTextBoxSize()
{
Size textSize = internalTextBox.GetPreferredSize(new Size(internalTextBox.Width, 0));
internalTextBox.Height = textSize.Height;
}
This does work when all the lines in the textbox are shorter than the Width. But when one line is longer and should be clipped to the next line, GetPreferredSize() returns a larger width than the one I passed, and therefore the height is too small.
So I changed again and tried this one:
private void AdaptTextBoxSize()
{
Size textSize = TextRenderer.MeasureText(
internalTextBox.Text,
internalTextBox.Font,
new Size(internalTextBox.Width, 0),
TextFormatFlags.WordEllipsis
);
internalTextBox.Height = textSize.Height;
}
This time the returned Width is correct, as it does not exceed the one I passed, but the height is the same as the previous trial. So it doesn't work either. I tried different combinations for TextFormatFlags, but could not manage to find the winning one...
Is this a bug from the framework?
The real question here is, is there another thing I can try, or another to achieve what I want (i.e. auto-adapt the height when setting the TextToDisplay property)?
TextBox.GetPositionFromCharIndex returns the pixel position of a character. Position here means top/left so we need to add one more line..
This seems to work here:
textBox.Height = textBox.GetPositionFromCharIndex(textBox4.Text.Length - 1).Y + lineHeight;
I get the line height like this:
int lineHeight = -1;
using (TextBox t = new TextBox() { Font = textBox.Font }) lineHeight = t.Height;
I set the Height instead of the ClientSize.Height, which is slightly wrong unless BorderStyle is None. You can change to textBox.ClientSize = new Size(textBox.ClientSize.Width, l + lh);

Panel alignment error with respect to label

I am adding a new way to distinguish the user privileges in my program.
It is a small circular panel that appears after the username and that changes color depending on its privileges and that is shown after the user nick leaving a spacing of 5 pixels
:
private void SetNick(string nick)
{
this.NickLabel.Text = nick;
this.NickLabel.Left = ((this.ProfilePicturePanel.ClientSize.Width - this.NickLabel.Width) / 2) - 5;
Hector.Framework.Utils.Ellipse.Apply(this.BadgePanel, 6);
this.BadgePanel.Top = this.NickLabel.Top + 3;
this.BadgePanel.Left = this.NickLabel.Width + this.BadgePanel.Width + 5;
}
The nick of the user has a minimum of 3 characters and a maximum of 6 characters, then when the nickname has 6 characters (example: Jhon S), the panel is aligned correctly:
But if the nickname have 3 characters (example: Ben), then this happens:
It is assumed that the panel should always be shown near the label leaving a space of 5 pixels even if the label changes its content.
Could you tell me what I'm doing wrong?
You can override the Label Control and write your own implementation that draws your badge directly in the Label. Here's a simple example.
public class LabelWithBadge : Label
{
public Color BadgeColor { get; set; }
private Size BadgeSize { get; set; }
public LabelWithBadge()
{
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);
if (BadgeColor == null)
BadgeColor = Color.Red;
if (BadgeSize == null)
BadgeSize = new Size(20, 20);
}
protected override Size SizeFromClientSize(Size clientSize)
{
var textSize = TextRenderer.MeasureText("doesn't matter", this.Font);
this.BadgeSize = new Size(textSize.Height, textSize.Height);
var baseSize = base.SizeFromClientSize(clientSize);
return new Size(baseSize.Width + BadgeSize.Width, baseSize.Height);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.FillEllipse(new SolidBrush(this.BadgeColor), this.ClientSize.Width - this.BadgeSize.Width, 0, this.BadgeSize.Width, this.BadgeSize.Height);
}
}
By overriding SizeFromClientSize you can control the AutoSize ability of the label, and pad it to make room for your badge.
If you want to support manual sizing for the badge, then you'll need to tweak this to work with AutoSize off.
Then I set Styles on the control to handle painting. Overriding OnPaint allows you to draw in the extra padded on in the SizeFromClientSize override.
I added a property for the Badge Color. The Badge Size is determined by the font on the control using TextRenderer.MeasureText. So if you make the font bigger, the badge get's bigger with it.
This control will show up in your Toolbox when you build. Then you can use it like any other label but this one has a badge in it.

How to truncate a string to fit in a container?

There are a lot of questions (EG: 1, 2, 3, 4, 5) asking how you can truncate a string to a desired amount of characters. But I want a piece of text truncated to fit in a container. (IE: crop the string by it's width in pixels, not characters).
This is easy if you use WPF, but not so much in WinForms...
So: how can you truncate a string to make it fit in a container?
After a day of coding I found a solution and I wanted to share it with the community.
First of all: there is no native truncate function for a string or winforms TextBox. If you use a label, you can use the AutoEllipsis property.
FYI: An ellipsis is a punctuation mark that consist of three dots. IE: …
That's why I made this:
public static class Extensions
{
/// <summary>
/// Truncates the TextBox.Text property so it will fit in the TextBox.
/// </summary>
static public void Truncate(this TextBox textBox)
{
//Determine direction of truncation
bool direction = false;
if (textBox.TextAlign == HorizontalAlignment.Right) direction = true;
//Get text
string truncatedText = textBox.Text;
//Truncate text
truncatedText = truncatedText.Truncate(textBox.Font, textBox.Width, direction);
//If text truncated
if (truncatedText != textBox.Text)
{
//Set textBox text
textBox.Text = truncatedText;
//After setting the text, the cursor position changes. Here we set the location of the cursor manually.
//First we determine the position, the default value applies to direction = left.
//This position is when the cursor needs to be behind the last char. (Example:"…My Text|");
int position = 0;
//If the truncation direction is to the right the position should be before the ellipsis
if (!direction)
{
//This position is when the cursor needs to be before the last char (which would be the ellipsis). (Example:"My Text|…");
position = 1;
}
//Set the cursor position
textBox.Select(textBox.Text.Length - position, 0);
}
}
/// <summary>
/// Truncates the string to be smaller than the desired width.
/// </summary>
/// <param name="font">The font used to determine the size of the string.</param>
/// <param name="width">The maximum size the string should be after truncating.</param>
/// <param name="direction">The direction of the truncation. True for left (…ext), False for right(Tex…).</param>
static public string Truncate(this string text, Font font, int width, bool direction)
{
string truncatedText, returnText;
int charIndex = 0;
bool truncated = false;
//When the user is typing and the truncation happens in a TextChanged event, already typed text could get lost.
//Example: Imagine that the string "Hello Worl" would truncate if we add 'd'. Depending on the font the output
//could be: "Hello Wor…" (notice the 'l' is missing). This is an undesired effect.
//To prevent this from happening the ellipsis is included in the initial sizecheck.
//At this point, the direction is not important so we place ellipsis behind the text.
truncatedText = text + "…";
//Get the size of the string in pixels.
SizeF size = MeasureString(truncatedText, font);
//Do while the string is bigger than the desired width.
while (size.Width > width)
{
//Go to next char
charIndex++;
//If the character index is larger than or equal to the length of the text, the truncation is unachievable.
if (charIndex >= text.Length)
{
//Truncation is unachievable!
//Throw exception so the user knows what's going on.
throw new IndexOutOfRangeException("The desired width of the string is too small to truncate to.");
}
else
{
//Truncation is still applicable!
//Raise the flag, indicating that text is truncated.
truncated = true;
//Check which way to text should be truncated to, then remove one char and add an ellipsis.
if (direction)
{
//Truncate to the left. Add ellipsis and remove from the left.
truncatedText = "…" + text.Substring(charIndex);
}
else
{
//Truncate to the right. Remove from the right and add the ellipsis.
truncatedText = text.Substring(0, text.Length - charIndex) + "…";
}
//Measure the string again.
size = MeasureString(truncatedText, font);
}
}
//If the text got truncated, change the return value to the truncated text.
if (truncated) returnText = truncatedText;
else returnText = text;
//Return the desired text.
return returnText;
}
/// <summary>
/// Measures the size of this string object.
/// </summary>
/// <param name="text">The string that will be measured.</param>
/// <param name="font">The font that will be used to measure to size of the string.</param>
/// <returns>A SizeF object containing the height and size of the string.</returns>
static private SizeF MeasureString(String text, Font font)
{
//To measure the string we use the Graphics.MeasureString function, which is a method that can be called from a PaintEventArgs instance.
//To call the constructor of the PaintEventArgs class, we must pass a Graphics object. We'll use a PictureBox object to achieve this.
PictureBox pb = new PictureBox();
//Create the PaintEventArgs with the correct parameters.
PaintEventArgs pea = new PaintEventArgs(pb.CreateGraphics(), new System.Drawing.Rectangle());
pea.Graphics.PageUnit = GraphicsUnit.Pixel;
pea.Graphics.PageScale = 1;
//Call the MeasureString method. This methods calculates what the height and width of a string would be, given the specified font.
SizeF size = pea.Graphics.MeasureString(text, font);
//Return the SizeF object.
return size;
}
}
Usage:
This is a class you can copy and paste in the namespace that contains your winforms form. Make sure you include "using System.Drawing;"
This class has two extensions methods, both called Truncate. Basically you can now do this:
public void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.Truncate();
}
You can now type something in textBox1 and if needed, it will automatically truncate your string to fit in the textBox and it will add an ellipsis.
Overview:
This class currently contains 3 methods:
Truncate (extension for TextBox)
Truncate (extension for string)
MeasureString
Truncate (extension for TextBox)
This method will automatically truncates the TextBox.Text property. The direction of truncation is determent by the TextAlign property. (EG: "Truncation for left alignm…", "…ncation for right alignment".) Please note: this method might need some altering to work with other writing systems such as Hebrew or Arabic.
Truncate (extension for string)
In order to use this method you must pass two parameters: a font and a desired width. The font is used to calculate the width of the string and the desired width is used as the maximum width allowed after truncation.
MeasureString
This method is private in the code snippet. So if you want to use it, you must change it to public first. This method is used to measure the height and width of the string in pixels. It requires two parameters: the text to be measured and the font of the text.
I hope I helped someone with this. Perhaps there is an other way to do this, I found this answer by Hans Passant, which truncates a ToolTipStatusLabel, which is quite impressive. My .NET skills are nowhere near that of Hans Passant so I haven't managed to convert that code to work with something like a TextBox... But if you did succeeed, or have another solution I would love to see it! :)
I tested the code of Jordy and compared the result with this code of mine, there is no difference, they both trim/truncate fairly OK but not well in some cases, that may be the size measured by MeasureString() is not exact. I know this code is just a simplified version, I post it here if someone cares about it and uses it because it's short and I tested: there is no difference in how exactly this code can trim/truncate string compared with the Jordy's code, of course his code is some kind of full version with 3 methods supported.
public static class TextBoxExtension
{
public static void Trim(this TextBox text){
string txt = text.Text;
if (txt.Length == 0 || text.Width == 0) return;
int i = txt.Length;
while (TextRenderer.MeasureText(txt + "...", text.Font).Width > text.Width)
{
txt = text.Text.Substring(0, --i);
if (i == 0) break;
}
text.Text = txt + "...";
}
//You can implement more methods such as receiving a string with font,... and returning the truncated/trimmed version.
}

Automatically Word-Wrapping Text To A Print Page?

I have some code that prints a string, but if the string is say: "Blah blah blah"... and there are no line breaks, the text occupies a single line. I would like to be able to shape the string so it word wraps to the dimensions of the paper.
private void PrintIt(){
PrintDocument document = new PrintDocument();
document.PrintPage += (sender, e) => Document_PrintText(e, inputString);
document.Print();
}
static private void Document_PrintText(PrintPageEventArgs e, string inputString) {
e.Graphics.DrawString(inputString, new Font("Courier New", 12), Brushes.Black, 0, 0);
}
I suppose I could figure out the length of a character, and wrap the text manually, but if there is a built in way to do this, I'd rather do that. Thanks!
Yes there is the DrawString has ability to word wrap the Text automatically. You can use MeasureString method to check wheather the Specified string can completely Drawn on the Page or Not and how much space will be required.
There is also a TextRenderer Class specially for this purpose.
Here is an Example:
Graphics gf = e.Graphics;
SizeF sf = gf.MeasureString("shdadj asdhkj shad adas dash asdl asasdassa",
new Font(new FontFamily("Arial"), 10F), 60);
gf.DrawString("shdadj asdhkj shad adas dash asdl asasdassa",
new Font(new FontFamily("Arial"), 10F), Brushes.Black,
new RectangleF(new PointF(4.0F,4.0F),sf),
StringFormat.GenericTypographic);
Here i have specified maximum of 60 Pixels as width then measure string will give me Size that will be required to Draw this string. Now if you already have a Size then you can compare with returned Size to see if it will be Drawn properly or Truncated
I found this : How to: Print a Multi-Page Text File in Windows Forms
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
int charactersOnPage = 0;
int linesPerPage = 0;
// Sets the value of charactersOnPage to the number of characters
// of stringToPrint that will fit within the bounds of the page.
e.Graphics.MeasureString(stringToPrint, this.Font,
e.MarginBounds.Size, StringFormat.GenericTypographic,
out charactersOnPage, out linesPerPage);
// Draws the string within the bounds of the page
e.Graphics.DrawString(stringToPrint, this.Font, Brushes.Black,
e.MarginBounds, StringFormat.GenericTypographic);
// Remove the portion of the string that has been printed.
stringToPrint = stringToPrint.Substring(charactersOnPage);
// Check to see if more pages are to be printed.
e.HasMorePages = (stringToPrint.Length > 0);
}
Dude im suffering with printing in HTML, total nightmare. I would say that in my opinion you should try use something else to print out the text etc pass parameters to reporting services and popup a PDF which the user can print off.
Or potentially you might need to count out the number of characters and explicitly specify a line break!

AutoSize for Label / TextBox in .NET Compact Framework

I'm quite simply going totally bonkers with the omission of the AutoSize-property for the Label and TextBox controls in .NET Compact Framework. I have a simple app, that's supposed to list a bunch of text data (generally between one-liners to a few paragraphs of text) in a TabControl. Everything else works smoothly, but my attempts at dynamically resizing the Label / TextBox -controls I use to display the text are failing miserably.
Here's the way I've tried doing it:
/*
Variables:
s = The text intended for the TextBox
NewTB = TextBox object
width = Intended width
whiteSpaceAdjustment = amount of pixels per line to adjust "wasted" whitespace due to wrapping
*/
String[] linesArray = s.Replace(Environment.NewLine, "\n").Split(new char[] { '\n' });
int lines = 0;
int lineHeight = g.MeasureString(
s.Replace("\n", "").Replace("\r", ""),
LabelFont
).ToSize().Height;
foreach (String str in linesArray) {
if (str.Length == 0) {
lines++;
continue;
}
szz = g.MeasureString(str, LabelFont).ToSize();
lines += szz.Width / (width - whiteSpaceAdjustment);
lines += (szz.Width % width) != 0 ? 1 : 0;
}
NewTB.Height = lines * lineHeight;
NewTB.Width = width;
...but the problem is that the range needed for whiteSpaceAdjustment is too huge. When it's large enough to actually work on the most extreme cases (paragraphs made mostly up of really long words), most boxes end up being a line or two too tall.
I'm probably going to have to implement word wrapping myself, but before I go there, is there anybody with a nice clean solution ready for this?
I'd be forever grateful!
Try this article
www.mobilepractices.com/2007/12/multi-line-graphicsmeasurestring.html
Make sure you also look at the link at the bottom of the article to be able to use different fonts.
If you are using .Net CF 3.5 you may be able to turn their example into an extension method. Otherwise I'd suggest that you create a new control inheriting from the framework control.
This is what I developed for auto re-size width of label in WinCE.
/// <summary>
/// This class provides dynamic size labels, i.e. as the text grows lable width will grow with it.
/// </summary>
public partial class AutoSizeLabel : UserControl
{
private string _strText;
private const int padding = 10;
public AutoSizeLabel()
{
InitializeComponent();
}
public override string Text
{
get
{
return _strText;
}
set
{
_strText = value;
Refresh();
}
}
protected override void OnPaint(PaintEventArgs pe)
{
SizeF size = pe.Graphics.MeasureString(this.Text, this.Font);
this.Size = new Size((int)size.Width + padding, this.Height);
if (this.Text.Length > 0)
{
pe.Graphics.DrawString(this.Text,
this.Font,
new SolidBrush(this.ForeColor),
(this.ClientSize.Width - size.Width) / 2,
(this.ClientSize.Height - size.Height) / 2);
}
// Calling the base class OnPaint
base.OnPaint(pe);
}
}

Categories

Resources