GroupBox.AutoSize and GroupBox.Text wrapping - c#

I have two problems with the GroupBox, they appears after setting GroupBox.AutoSizeMode = AutoSizeMode.GrowAndShrink and GroupBox.AutoSize = true.
GroupBox.Text width is not taken into account at all. Sizing will occurs to fit content only and then text will get wrapped if it doesn't fit. If it cannot fit - it is simply not displayed.
There is unnecessarily big gap between bottom of the GroupBox and Label inside.
Questions:
How to make GroupBox respecting its Text property when autosizing? And how to remove that gap?
For some reasons my previous question gets on hold. Should I delete it or what?
P.S.: if you are putting on hold or something, please comment what is exactly not-clear in what I am asking!

/*
Calculate the Text Width in pixels, then set the size for the GroupBox.
*/
groupBoxA.SuspendLayout();
SizeF stringSizeLabel;
using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(new Bitmap(1, 1)))
{
Font stringFont = new Font("Microsoft Sans Serif", 8.25F);
stringSizeLabel = graphics.MeasureString("SAMPLE TEXT", stringFont);
}
int iWidth = (int)(stringSizeLabel.Width * 1.35f); // Give a little extra width
int iHeight = 78; // This is a sample value
groupBoxA.Size = new System.Drawing.Size(iWidth, iHeight);
groupBoxA.MinimumSize = new System.Drawing.Size(iWidth, iHeight);
groupBoxA.ResumeLayout(false);
groupBoxA.PerformLayout();

Related

How to set CheckedBoxList to MaxWidth of Item Conents

I have tried a lot of things.
Rectangle r = checkedListBox1.GetItemRectangle(0);
checkedListBox1.ClientSize = new Size(checkedListBox1.PreferredSize.Width, checkedListBox1.PreferredSize.Height);
Here I tried resizing the ClientSize to the PreferredSizes, this doesn't seem to always work. An odd note is that PreferredSize.Height is not always correct if I don't previously call GetItemRectangle().
I have tried capturing the maximum bounds on OnDrawItem with no luck because this only gives information about whats being painted.
I have tried iterating over each element using TextRenderer.MeasureText()
I have tried creating a fake graphics class along with graphics.MeasureString() to measure it in a simular fashion to which it was painted.
foreach (string selection in this.Items)
{
Image tmpImg = new Bitmap(1, 1);
Graphics graphics = Graphics.FromImage(tmpImg);
StringFormat format = new StringFormat(StringFormat.GenericTypographic);
format.Trimming = StringTrimming.None;
format.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces;
SizeF size = graphics.MeasureString(selection, this.Font, 0, format);
float selectionWidth = size.Width + PaddingRecommendedByMSDN + CustomCheckBoxWidth;
if (selectionWidth > maxWidth)
maxWidth = (int)selectionWidth;
}
Rectangle r = this.GetItemRectangle(0);
this.ClientSize = new Size((int)maxWidth , this.PreferredSize.Height );
Although this last solution seems to be the most accurate. It still is slightly off on large strings.
Does anyone know where I can properly capture the maximum width of the item contents of a CheckedListBox? I'm just trying to make the width fill the CheckedListBox so there are no scrolls shown. PreferredSize.Height never seems to fail me, only the width.
Trying using TextRenderer.MeasureText instead:
Size size = TextRenderer.MeasureText(selection, this.Font);
TextRenderer uses GDI to render the text, whereas Graphics uses GDI+. The two use a slightly different method for laying out text so the sizes are different.
If the text will be displayed inside a Windows Forms control (in your case it will), it uses TextRenderer if UseCompatibleTextRendering is set to false (which is the default).
More generic information can be found here:
TextRenderer.MeasureText and Graphics.MeasureString mismatch in size

Fit text on a custom component

I am trying to create a 'jeopardy' type game and i have gotten to the point where you just have to click on a box and a question box will appear.
Im using a customPictureBox, essentially overriding text and such:
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
Size size = TextRenderer.MeasureText(text, font);
int x = Width / 2 - size.Width / 2;
int y = Height / 2 - size.Height / 2;
pe.Graphics.DrawString(text, font, new SolidBrush(color), x, y);
}
on the game i add its properties like this:
CustomPictureBox box = new CustomPictureBox()
{
Text = ((QuestionBox)sender).Question.Text.ToUpper(),
SizeMode = PictureBoxSizeMode.StretchImage,
Font = new Font("Comic Sans MS", 40),
Image = Properties.Resources.MainTile,
ForeColor = Color.White,
BorderStyle = BorderStyle.FixedSingle,
Dock = DockStyle.Fill
};
The problem comes when the text length exceeds certain amount of (depending on the monitor) words, essentially what happens is that the text is drawn but a majority of it goes outside of the form, adding Autosize and Maximum size
Reference, this adds the MaxSize to the whole CustomPictureBox.
This solution seems to put an offset for the words, making longer sentences fly completely off the screen.
Ideally I need to add a newline til the words reach a preset boundary so they wouldn't go off the form.
Do not use Graphics.DrawString, use TextRenderer.DrawText instead.
Specifically, use this overload since it accepts
IDeviceContext - that's your Graphics instance, 
String - that's the string to draw,
Font - that's the font to use, 
Rectangle - that's the rectangle to use for boundaries, 
Color - that's the fore color to use, 
And TextFormatFlags - that's a flags enum that allows you to specify how to wrap text - using either default or WordBreak.
So, replace this row:
pe.Graphics.DrawString(text, font, new SolidBrush(color), x, y);
With this:
var flags = TextFormatFlags.HorizontalCenter |
TextFormatFlags.VerticalCenter |
TextFormatFlags.WordBreak;
TextRenderer.DrawText(pe.Graphics, text, font, pe.ClipRectangle, ForeColor, flags);

C# ListView, View=List - How to get rid of unused space at the bottom?

In a C# ListView with View=List, there is empty space at the bottom, reserved for a scrollbar. Weirdly, setting Scrollable=false will only increase the size of this unused space.
How can I get rid of this space or make sure it's used to display items?
Edit:
I'm having this issue in a Windows Form Application.
Edit 2: The issue seems to be coupled with the font size somehow. I need the font size to be 9 pt. With 11 pt this problem doesn't appear.
Edit 3: I also tried Item spacing in ListView where View=List but that didn't help either.
Edit 4: It happens under Win7 with the Win7 Theme. However, at least with Scrollable = false, it doesn't happen with the Classic Theme.
Still hoping for a more elegant solution, but for now, I found this workaround:
One can use a Panel to get rid of the extra space. I got the idea from TaW's answer to Add padding to last ListView item in WinForms
Remember, this worked for me, because I don't want or need a Scrollbar.
listView1.Scrollable = true;
int itemHeight = listView1.GetItemRect(0).Height;
int numItemsPerColumn = 10;
//One needs to add 21 to the height, because even if no Scrollbar
//is needed, that space will stay reserved.
listView1.Size = new Size(500, itemHeight * numItemsPerColumn + 21);
Panel P = new Panel();
P.BackColor = listView1.BackColor;
P.Location = listView1.Location;
//The height you actually want
P.Size = new Size(500, itemHeight * numItemsPerColumn + 4);
P.BorderStyle = listView1.BorderStyle;
listView1.BorderStyle = BorderStyle.None;
listView1.Parent = P;
listView1.Location = new Point(0, 0);
this.Controls.Add(P);

c# dynamically created label size not wide enough

When dynamically creating a label a part of it's text is missing. This is because the size of the label is not wide enough, it cuts of a part of the the actual string.
How do i make that simply stop? I dont want to nor do i remember setting a size to the label. Should it not just continue untill the string is empty?
Example: value = "Berserker's Iron Axe", it only displays "Berserker's Iron", because i have no size set it cust off a part of the string.
PictureBox finalResult_pBox = new PictureBox {
Name = "finalResult_pBox" + i,
Size = new Size(64, 64),
Padding = new Padding(0),
BorderStyle = BorderStyle.FixedSingle,
ImageLocation = spidyApi_idByName_result.results[i].img.ToString(),
};
MessageBox.Show(spidyApi_idByName_result.results[i].name.ToString());
Label finalResult_itemName_label = new Label{
Name = "finalResult_itemName_label" + i,
Text = spidyApi_idByName_result.results[i].name,
};
FlowLayoutPanel finalResult_panel = new FlowLayoutPanel{
FlowDirection = FlowDirection.TopDown,
BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle,
Name = "result_flowLayoutPanel" + i,
Size = new System.Drawing.Size(790, 64),
TabIndex = i,
};
finalResult_panel.Controls.Add(finalResult_pBox);
finalResult_panel.Controls.Add(finalResult_itemName_label);
result_flowLayoutPanel.Controls.Add(finalResult_panel);
Why is this happening and how do i fix this?
As long as you keep Label.AutoSize = true, which is the default it should size itself automatically.
You may want to do some tests to see the actual dimensions, like
setting a BorderStyle
or a BackColor
or inserting a space in the Text, so it gets a chance to go to a second line..
Of course you could measure the Text (with e.g. TextRenderer.MeasureText(text, Label.Font); but that will certainly not be necessary for the text simply to show.. It is useful for more demanding layout control, though.
So the first thing is to make sure that AutoSize is either true or that you measure and set the Size of the Label..

C# Chart Control produces huge title for large heights

I'm developing several bar charts using chart controls in C#, one of which holds a series of ~2300 data points. In order to be able to properly display custom labels for each data point, I expanded the height of the chart to be 10000. However, it's now producing quite a large sized header and footer for the chart, as seen below:
When I set the chart to resume having a more normal height of 500, though, the title size goes back to being more reasonable. How can I manually adjust the title size?
Here's my code for the chart properties:
Chart chart = new Chart();
chart.Width = 1000;
chart.Height = 10000;
chart.BackColor = Color.FromArgb(211, 223, 240);
chart.BorderlineDashStyle = ChartDashStyle.Solid;
chart.BackGradientStyle = GradientStyle.TopBottom;
chart.BorderlineWidth = 1;
chart.Palette = ChartColorPalette.Bright;
chart.BorderlineColor = Color.FromArgb(26, 59, 105);
chart.RenderType = RenderType.BinaryStreaming;
chart.BorderSkin.SkinStyle = BorderSkinStyle.Emboss;
chart.AntiAliasing = AntiAliasingStyles.All;
chart.TextAntiAliasingQuality = TextAntiAliasingQuality.Normal;
chart.Titles.Add("Hit Rate");
chart.IsSoftShadows = true;
chart.ChartAreas.Add("Left");
chart.ChartAreas["Left"].AxisX.Title = "Market Area";
chart.ChartAreas["Left"].AxisY.Title = "Hit Percentage";
UPDATE: I have added this to my code...
chart.ChartAreas["Left"].InnerPlotPosition.X = 5;
chart.ChartAreas["Left"].InnerPlotPosition.Y = 0f;
which has helped somewhat. In addition, I have found that it is not the size of the title in and of itself that is causing the problem. The height of the title is actually quite normal. Instead it is all the blank space allocated to the chart above the actual graphing area.
Let's try this :
chart.Titles[0].Position.Auto = false;
chart.Titles[0].Position.Width = 60; //change the size you want
auto = false means you manually calculate the location. I think by default the width of the title is 50% and 50% of the chart.
Ludo
Instead of setting the height and width of the chart manually why don't you leave it to set automatically according to the content and set the below:
chart.ChartAreas[0].AxisX.Interval = 1;
chart.ChartAreas[0].AxisY.Interval = 1;
(here i'm choosing chart area 0, change it according to your code)
As you add the above code do not set the height and width of the chart.
Let me know in case of issues

Categories

Resources