I would like to set my ListBox.Width property so that it is no wider nor narrower than needed, in order to display the items in it. There is a margin of a few pixels between the left of the ListBox and the start of the text - I would like there to be a similar margin on the right. (i.e. there shouldn't be a large gap, and the letters shouldn't be touching the right edge).
Given that I'm not sure how many pixels a given string will be, I'm not sure how to calculate this width.
I believe you're looking for the MeasureString method of the Graphics class.
Try this:
Graphics graphics = this.createGraphics();
SizeF mySize = graphics.MeasureString("Ahoy there", this.Font);
Hope this helps!
This may be what you want. Also play around with Integral Height and padding.
http://www.codeproject.com/KB/combobox/resizablelistbox.aspx
This worked for me, it wasn't until I changed the width of the listbox that I saw the results I wanted. I looped through the items in the listbox to get the longest. Hope this helps.
int LongestItemLength = 0;
for (int i = 0; i < listBox1.Items.Count;i++ ){
Graphics g = listBox1.CreateGraphics();
int tempLength = Convert.ToInt32((
g.MeasureString(
listBox1.Items[i].ToString(),
this.listBox1.Font
)
).Width);
if (tempLength > LongestItemLength){
LongestItemLength = tempLength;
}
}
listBox1.Width = LongestItemLength;
listBox1.Show();
Related
I added a new chart control (System.Windows.Forms.DataVisualiation.Charting) with ChartType Bar.
As requirement the label text must be white and into the bar value. Therefore I set the BarLabelStyle=Right in the CustomProperties of the DataPoint objects and the LabelForeColor to White.
See the below images.
The label in the 2nd gray bar is correctly shown.
The first bar instead is too small and the white text is shown out on the right side but is not visible.
However, when the bar is too short, the label text is positioned outside the bar and the text cannot be seen using white color.
Is there a way to check when the label text is drawn outside the bar value so that I can change the color (e.g. black)?
Thanks.
Unfortunately MCChart has almost no capacities wrt to dynamic expressions.
To work around you can either..:
Code the ForeColor depending on the y-value your DataPoints has. Either right when you add them or in a function that loops over all points, whenever you call it.. - Depending on the Font, the axis range and the label text this could be some threshold number you have to determine.
Example:
int p = yourSeries.Points.AddXY(...);
yourSeries.Points[p].LabelForeColor = yourSeries.Points[p].YValues[0] < threshold ?
Color.Black : Color.White;
Or you can cheat a little ;-)
You can set the LabelBackColor to have the same color as the Series, i.e. the bar itself. Here is is how to do that:
To access the Series.Color we have to call:
chart.ApplyPaletteColors();
Now we can set
yourSeries.LabelForeColor = Color.White;
yourSeries.LabelBackColor = yourSeries.Color;
Example:
Update:
Since you can't use the cheat you will have to set the colors.
The challenge is to know just how much space each label's text needs compared to how much space the bars have. The former can be measured (TextRenderer.MeasureString()) and the latter can be extracted from the y-axis (Axis.ValueToPixelPosition()).
Here is a function to do that; it is a little more complicated than I had hoped for, mostly because it tries to be generic..
void LabelColors(Chart chart, ChartArea ca, Series s)
{
if (chart.Series.Count <= 0 || chart.Series[0].Points.Count <= 0) return;
Axis ay = ca.AxisY;
// get the maximum & minimum values
double maxyv = ay.Maximum;
if (maxyv == double.NaN) maxyv = s.Points.Max(v => v.YValues[0]);
double minyv = s.Points.Min(v => v.YValues[0]);
// get the pixel positions of the minimum
int y0x = (int)ay.ValueToPixelPosition(0);
for (int i = 0; i < s.Points.Count; i++)
{
DataPoint dp = s.Points[i];
// pixel position of the bar right
int vx = (int)ay.ValueToPixelPosition(dp.YValues[0]);
// now we knowe the bar's width
int barWidth = vx - y0x;
// find out what the label text actauly is
string t = dp.LabelFormat != "" ?
String.Format(dp.LabelFormat, dp.YValues[0]) : dp.YValues[0].ToString();
string text = dp.Label != "" ? dp.Label : t;
// measure the (formatted) text
SizeF rect = TextRenderer.MeasureText(text, dp.Font);
Console.WriteLine(text);
dp.LabelForeColor = barWidth < rect.Width ? Color.Black : Color.White;
}
}
I may have overcomplicated the way to get at the text that should show; you certainly can decide if you can simplify for your case.
Note: You must call this function..
whenever your data may have changed
only after the axes of the chart have finished their layout (!)
The former point is obvious, the latter isn't. It means that you can't call the function right after adding your points! Instead you must do it at some later place or else the axis function needed to get the bar size will not work.
MSDN says it can only happen in a PaintXXX event; I found that all mouse events also work and then some..
To be save I'll put it in the PostPaint event:
private void chart_PostPaint(object sender, ChartPaintEventArgs e)
{
LabelColors(chart, chart.ChartAreas[0], chart.Series[0]);
}
I want to make a chart in C# with custom elements. What I have:
What I want:
Elements marked by red circles need to be replaced by the image. My program code is very short, just some values for the chart. All settings for chart were set by the "Collection" in Chart section (as shown on first image).
This is a BoxPlot chart and it takes 6 y-values.
You can add them or let the chart calculate them.
Looks like you want to add several images to the various y-values..
Here is an example of how to do that by owner-drawing the Chart. (No, not the whole chart, just a little extra custom-drawing ;-)
It adds an image to each of the y-values; it should be easy to adapt to only those values you really want. And if you only want one you may even do away with the ImageList and pick the image from the resources; (although using an ImageList is a nice way, as long as you can live with the limitations of 256x256 maximum size and all images having the same size and color depth..)
You seem to want one of these only:
4 Average and mean
5 Median
private void chart_PostPaint(object sender, ChartPaintEventArgs e)
{
Series s1 = chart.Series[0];
ChartArea ca = chart.ChartAreas[0];
Axis ax = ca.AxisX;
Axis ay = ca.AxisY;
Graphics g = e.ChartGraphics.Graphics;
int iw = imageList1.ImageSize.Width / 2;
int ih = imageList1.ImageSize.Height / 2;
foreach (DataPoint dp in s1.Points)
{
int x = (int) ax.ValueToPixelPosition(dp.XValue);
for (int i = 0; i < 6; i++)
{
int y = (int) ay.ValueToPixelPosition(dp.YValues[i]);
g.DrawImage(imageList1.Images[i], x - iw, y - ih);
}
}
}
I suggest to use png files with transparency and an odd width so they look nice and centered. (I used randomly 16x16, which is not quite that nice ;-) - For this you need to set the ImageSize and the ColorDepth of the ImageList.
To further style the chart you may use these special properties
Custom attributes
BoxPlotPercentile, BoxPlotSeries, BoxPlotShowAverage,
BoxPlotShowMedian, BoxPlotShowUnusualValues, BoxPlotWhiskerPercentile,
DrawSideBySide, MaxPixelPointWidth, MinPixelPointWidth,
PixelPointDepth, PixelPointGapDepth, PixelPointWidth, PointWidth
Note that you need to set them all as strings, maybe like this:
s1.SetCustomProperty("someAttribute", "someValue");
I need to graph rectangles of different heights and widths in a C# application. The rectangles may or may not overlap.
I thought the System.Windows.Forms.DataVisualization.Charting would have what I need, but every chart type I've explored wants data points composed of a single value in one dimension and multiple values in the other.
I've considered: Box, Bubble, and Range Bar.
It turns out that Richard Eriksson has the closest answer in that the Charting package doesn't contain what I needed. The solution I'm moving forward with is to use a Point chart to manage axes and whatnot, but overload the PostPaint event to effectively draw the rectangles I need on top. The Chart provides value-to-pixel (and vice versa) conversions.
Here is a minimal example that throws 100 squares of different colors and sizes randomly onto one Chart of ChartType Point with custom Marker Images.
You can modify to de-couple the datapoints from the colors, allow for any sizes or shapes etc..:
int count = 100;
int mSize = 60; // marker size
List<Color> colors = new List<Color>(); // a color list
for (int i = 0; i < count; i++)
colors.Add(Color.FromArgb(255, 255 - i * 2, (i*i) %256, i*2));
Random R = new Random(99);
for (int i = 0; i < count; i++) // create and store the marker images
{
int w = 10 + R.Next(50); // inner width of visible marker
int off = (mSize - w) / 2;
Bitmap bmp = new Bitmap(mSize, mSize);
using (Graphics G = Graphics.FromImage(bmp))
{
G.Clear(Color.Transparent);
G.FillRectangle(new SolidBrush(colors[i]), off, off, w, w);
chart5.Images.Add(new NamedImage("NI" + i, bmp));
}
}
for (int i = 0; i < count; i++) // now add a few points to random locations
{
int p = chart5.Series["S1"].Points.AddXY(R.Next(100), R.Next(100));
chart5.Series["S1"].Points[p].MarkerImage = "NI" + p;
}
Note that this is really just a quick one; in the Link to the original answer about a heat map I show how to resize the Markers along with the Chart. Here they will always stay the same size..:
I have lowered the Alpha of the colors for this image from 255 to 155, btw.
The sizes also stay fixed when zooming in on the Chart; see how nicely they drift apart, so you can see the space between them:
This may or may not be what you want, of course..
Note that I had disabled both Axes in the first images for nicer looks. For zooming I have turned them back on so I get the simple reset button..
Also note that posting the screenshots here introduces some level of resizing, which doesn't come from the chart!
I want to be able to set the number of lines in a multilined TextBox.
I've tried the following:
int initHeight = textBox1.Height;
textBox1.Height = initHeight * numOfLines;
But this makes it too large when numOfLines gets large. So then I tried this:
float fontHeight = textBox1.CreateGraphics().MeasureString("W", textBox1.Font).Height;
textBox1.Height = fontHeight * numOfLines;
But this was too small when numOfLines was small, and too large when numOfLines was large.
So I'm doing SOMETHING wrong... any ideas?
This would set the exact Width & Height of your multi line Textbox:
Size size = TextRenderer.MeasureText(textBox1.Text, textBox1.Font);
textBox1.Width = size.Width;
textBox1.Height = size.Height + Convert.ToInt32(textBox1.Font.Size);
Something like this should work:
Size size = TextRenderer.MeasureText(textBox1.Text, textBox1.Font);
textBox1.Width = size.Width;
textBox1.Height = size.Height;
This was from C# Resize textbox to fit content
What you are doing should work, but you need to set the MinimumSize and MaximumSize I am not 100% positive, but I think this constraint will still hold if height is set via code
From the documentation of Graphics.MeasureString:
To obtain metrics suitable for adjacent strings in layout (for example, when implementing formatted text), use the MeasureCharacterRanges method or one of the MeasureString methods that takes a StringFormat, and pass GenericTypographic. Also, ensure the TextRenderingHint for the Graphics is AntiAlias.
As such, you should use one of these overloads, such as this one, which allow you to specify StringFormat.GenericTypograpic to get the required size.
Try this:
float fontHeight;
using (var g = textBox1.CreateGraphics())
fontHeight = g.MeasureString("W", textBox1.Font, new PointF(), StringFormat.GenericTypograpic).Height;
I'm trying to figure out a good way to auto-size a Rectangle that has text drawn inside of it. I basically want the size to have a ratio of width/height and then "grow" according to that ratio to fit the text. I've looked at Graphics.MeasureString but I don't think it does what I'm looking for (maybe it does and I'm just using it wrong).
I don't want to specify a specific width of the rectangle to be drawn. Instead I want to say find the smallest width/height to fit this text given a minimum width but the found rectangle must have some specific ratio of width and height.
This doesn't have to be specific to C#, any idea for solving this problem I'm sure can be mapped to C#.
Thanks!
I believe you can use Graphics.MeasureString. This is what I have used in my GUI code to draw rectangles around text. You hand it the text and the font you want to use, it returns to you a rectangle (technically a SizeF object - width and height). Then you can adjust this rectangle by the ratio you want:
Graphics g = CreateGraphics();
String s = "Hello, World!";
SizeF sizeF = g.MeasureString(s, new Font("Arial", 8));
// Now I have a rectangle to adjust.
float myRatio = 2F;
SizeF adjustedSizeF = new SizeF(sizeF.Width * myRatio, sizeF.Height * myRatio);
RectangleF rectangle = new RectangleF(new PointF(0, 0), adjustedSizeF);
Am I understanding your question correctly?
You should use TextRenderer.MeasureText, all controls use TextRenderer to draw text in .NET 2.0 and up.
There is no unambiguous solution to your question, there are many possible ways to fit text in a Rectangle. A wide one that displays just one line is just as valid as a narrow one that displays many lines. You'll have to constrain one of the dimensions. It is a realistic requirement, this rectangle is shown inside some other control and that control has a certain ClientSize. You'll need to decide how you want to lay it out.
On the back of my comment about the System.Windows.Forms.Label, maybe you could have a look at the code driving the painting of a Label? If you use Reflector this should get you part of the way.
There seems to be some methods on there like GetPreferredSizeCore() for example that probably have what you want which I'm sure could be made generic enough given a little work.
I've found my own solution. The following code determines the best rectangle (matching the ratio) to fit the text. It uses divide and conquer to find the closest rectangle (by decrementing the width by some "step"). This algorithm uses a min-width that is always met and I'm sure this could be modified to include a max width. Thoughts?
private Size GetPreferredSize(String text, Font font, StringFormat format)
{
Graphics graphics = this.CreateGraphics();
if (format == null)
{
format = new StringFormat();
}
SizeF textSize = SizeF.Empty;
// The minimum width allowed for the rectangle.
double minWidth = 100;
// The ratio for the height compared to the width.
double heightRatio = 0.61803399; // Gloden ratio to make it look pretty :)
// The amount to in/decrement for width.
double step = 100;
// The new width to be set.
double newWidth = minWidth;
// Find the largest width that the text fits into.
while (true)
{
textSize = graphics.MeasureString(text, font, (int)Math.Round(newWidth), format);
if (textSize.Height <= newWidth * heightRatio)
{
break;
}
newWidth += step;
}
step /= 2;
// Continuously divide the step to adjust the rectangle.
while (true)
{
// Ensure step.
if (step < 1)
{
break;
}
// Ensure minimum width.
if (newWidth - step < minWidth)
{
break;
}
// Try to subract the step from the width.
while (true)
{
// Measure the text.
textSize = graphics.MeasureString(text, font, (int)Math.Round(newWidth - step), format);
// If the text height is going to be less than the new height, decrease the new width.
// Otherwise, break to the next lowest step.
if (textSize.Height < (newWidth - step) * heightRatio)
{
newWidth -= step;
}
else
{
break;
}
}
step /= 2;
}
double width = newWidth;
double height = width * heightRatio;
return new Size((int)Math.Ceiling(width), (int)Math.Ceiling(height));
}