Text drawing "bold" - c#

So I'm writing a program that generates a chart and saves it to PNG. From what I've read, if I were drawing to a window, it doesn't behave this way, but I'm not doing that.
The problem is that when I pass the brush I use to draw the label to another method to do the drawing, sometimes the text comes out looking bold. Also, the Y coordinate seems to have something to do with it, since it happens on every other row of the chart I'm drawing. And it's not a nice bold, either, it's like a gritty, messy looking bold. Some people have suggested changing the text rendering hint to antialiased, and it solves the "bolding" problem, but it doesn't look as nice as ClearType.
Note that none of this happens if I do everything in one method without passing the brush around, which is the most puzzling part of this. Any ideas?
Here's some of the code:
// Draw the timeline.
int y = 0;
bool shadeRow = true;
foreach (TimelineRow row in timeline.chart)
{
int rowHeight = row.height + TimelineRow.ROW_GAP;
if (shadeRow)
{
g.FillRectangle(shadeBrush, 0, y, chartWidth, rowHeight);
}
// Draw name labels, guidelines, and timeline row.
g.DrawString(row.name, labelFont, labelBrush, PADDING, (int)Math.Ceiling(y + (float)PADDING / 2));
for (int i = 0; i < row.years.Length; i++)
{
int blockX = labelsWidth + i * TimelineRow.DEFAULT_HEIGHT;
g.DrawLine(i % 5 == 0 ? yearGridDark : yearGridLight, blockX, y, blockX, y + rowHeight);
}
DrawRow(row, g, labelsWidth, y + 8);
y += rowHeight;
shadeRow = !shadeRow;
}
// Draw the year labels
int x = labelsWidth;
for (int year = timeline.startYear; year <= timeline.endYear; year += 5)
{
string yearString = Convert.ToString(year);
int width = (int)g.MeasureString(yearString, labelFont).Width;
g.DrawString(yearString, labelFont, labelBrush, x - width / 2, y);
x += 5 * TimelineRow.DEFAULT_HEIGHT;
}

I've had similar issues with drawing strings. In my cases, clearing the image FIRST with the background color has fixed the problem.
Wow, that actually did it.
Use Graphics.Clear() to set the initial color:
Bitamp bmp = new Bitmap(...);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.White);
// ... now draw with "g" ...

Related

Setting fixed major grid marks independent of data range

This is my first project in c# and I'm trying to create plots from data.
I'm struggling with drawing minor and major grid lines and labels on a logarithmic scale.
I've set the scale to logarithmic, set the base to 10 and both major and minor intervals to 1, and it works great, however, the interval starts with the minimum value on scale, so for example if data starts at 30M (I'm dealing with frequencies) the next major tick is at 300M and 3G, which is not as it should be.
Is there a way to set major grid to 1, 10, 100 etc, independent of what data is displayed? i've tried changing intervals, base and offset but have not achieved much.
area.AxisX.IsLogarithmic = true;
area.AxisX.LogarithmBase = 10;
area.AxisX.Interval = 1;
//area.AxisX.IntervalOffset = 10000;
area.AxisX.IntervalAutoMode = IntervalAutoMode.FixedCount;
area.AxisX.MajorGrid.Enabled = true;
area.AxisX.MajorTickMark.Enabled = true;
area.AxisX.MinorGrid.Enabled = true;
area.AxisX.MinorGrid.Interval = 1;
area.AxisX.MinorTickMark.Enabled = true;
area.AxisX.MinorTickMark.Interval = 1;
area.AxisX.Minimum = minMaxXY[0]; // in this example 30 M
area.AxisX.Maximum = minMaxXY[1]; // in this example 1 G
here's the link to the current grid
https://ibb.co/3WkxLfc
Thank you for your time and answers!
Thanks to TaW replay I managed to get my program working.
Here is my solution using customLabels location to draw the grid lines.
private void Chart1_PostPaint(object sender, ChartPaintEventArgs e)
{
if (e.Chart.ChartAreas.Count > 0) // I don't yet truly understand when this event occurs,
// so I got plenty of null references.
{
Graphics g = e.ChartGraphics.Graphics;
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
Color minorGridColor = Color.Gainsboro;
ChartArea area = e.Chart.ChartAreas[0];
double aymin = area.AxisY.Minimum;
double aymax = area.AxisY.Maximum;
int y0 = (int)area.AxisY.ValueToPixelPosition(aymin);
int y1 = (int)area.AxisY.ValueToPixelPosition(aymax);
foreach (var label in chart1.ChartAreas[0].AxisX.CustomLabels)
{
double xposition = area.AxisX.ValueToPixelPosition(Math.Pow(10, label.FromPosition + 0.1));
if (xposition > area.AxisX.ValueToPixelPosition(minMaxXY[0]) && xposition < area.AxisX.ValueToPixelPosition(minMaxXY[1]))
//this prevents drawing of lines outside of the chart area
{
int x = (int)xposition;
using (Pen dashed_pen = new Pen(Color.FromArgb(10, 0, 0, 0), 1))
{
dashed_pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
g.DrawLine(dashed_pen, x, y0, x, y1);
}
}
}
}
}
I also found the CustomLabel.GridTicks Property, but for some reason it did not work.

How to detect where the image content ends?

I receive images of the same size but with different amounts of information. Examples below (red borders are mine). The background is always white.
I am trying to detect where the information on the image ends - at what pixel height (and crop accordingly). In other words, find the first non-white pixel from the bottom.
Is there a better way to do this other than extract BitmapData out of Image object and loop through all the pixels?
Just to add a suggestion having looked over your images and your solution (below) and your method is fine but you may be able to improve efficiency.
The more you know about your image the better; you're confident the background is always white (according to your post, the code is a more generic utility but the following suggestion can still work); can you be confident on the furthest point in a non-white pixel will be found if the row is not empty?
For example; in your two pictures the furthest in non-white pixel on a row is about 60px in. If this is universally true for your data then you don't need to scan the whole line of the image, which would make your for loop:
for (int y = bitmap.Height - 1; y >= 0; y--) {
for (int x = 0; x < 60; x++) {
Color color = bitmap.GetPixel(x, y);
if (color.R != backColor.R || color.G != backColor.G || color.B != backColor.B) {
foundContentOnRow = y;
break;
}
}
}
(You could make it a parameter on the function so you can easily control it if needed).
Imagine for example that the first non-white row was 80px down. To find it currently you do 640 x 300 = 192,000 checks. If you could confidently say that you would know a row was blank within 100 pixels (an over-estimate based on the data presented) then this would be 100 * 300 = 30,000 checks per image.
If you always knew that the first 10 pixels of the image were always blank you could shave a little bit more off (say 3000 checks).
Musing on a setup where you knew that the first non-white pixel was between 10 and 60 pixels in (range of 50) you could find it at row 80 in 50 x 300 = 15,000 checks which is a good reduction.
Of course the downside about assumptions is that if things change your assumptions may not be valid, but if the data is going to remain fairly constant then it may be worthwhile, especially if you do this for a lot of images.
I've ended up using the following code to trim the image. Hopefully someone finds this useful.
class Program {
static void Main(string[] args) {
Image full = Image.FromFile("foo.png");
Image cropped = full.TrimOnBottom();
}
}
public static class ImageUtilities {
public static Image TrimOnBottom(this Image image, Color? backgroundColor = null, int margin = 30) {
var bitmap = (Bitmap)image;
int foundContentOnRow = -1;
// handle empty optional parameter
var backColor = backgroundColor ?? Color.White;
// scan the image from the bottom up, left to right
for (int y = bitmap.Height - 1; y >= 0; y--) {
for (int x = 0; x < bitmap.Width; x++) {
Color color = bitmap.GetPixel(x, y);
if (color.R != backColor.R || color.G != backColor.G || color.B != backColor.B) {
foundContentOnRow = y;
break;
}
}
// exit loop if content found
if (foundContentOnRow > -1) {
break;
}
}
if (foundContentOnRow > -1) {
int proposedHeight = foundContentOnRow + margin;
// only trim if proposed height smaller than existing image
if (proposedHeight < bitmap.Height) {
return CropImage(image, bitmap.Width, proposedHeight);
}
}
return image;
}
private static Image CropImage(Image image, int width, int height) {
Rectangle cropArea = new Rectangle(0, 0, width, height);
Bitmap bitmap = new Bitmap(image);
return bitmap.Clone(cropArea, bitmap.PixelFormat);
}
}

Getting colour values from various positions in a bitmap c#

I have a bitmap and I am wanting to get the colour values from the pixels but only in certain areas of the image. I am wanting to the get the pixels of a image for the full width and only a bit of the height (say height =1) and then I want to move the position to one down and get the same values.
I am using
for (int i = 0; i < 302; i++)
{
Rectangle cloneRect = new Rectangle(0, i, 514, 1);
System.Drawing.Imaging.PixelFormat format = bm.PixelFormat;
Bitmap cloneBitmap = bm.Clone(cloneRect, format);
bitMapList.Add(cloneBitmap);
}
foreach (Bitmap bmp in bitMapList)
{
c = bmp.GetPixel(514, 1);
r = Convert.ToInt16(c.R);
lumi.Add(r);
}
The for statement to create the areas I want on the bitmap and then the foreach to loop through these bitmaps and then get the values. Only problem is I am getting the error message "Parameter must be positive and < Width."
On the line
c = bmp.GetPixel(514, 1);
anyone know why?
Thanks
You need to make sure that the pixel you are getting is inside of the image (which must not be the case). You could wrap this in a call to run a check first something like:
public static Color GetPixelSafe(Bitmap image, int x, int y) {
if (x >= image.Width) x = image.Width - 1;
else if (x < 0) x = 0;
if (y >= image.Height) y = image.Height - 1;
else if (y < 0) y = 0;
return image.GetPixel(x, y);
}
Now, this is not going to fix your processing algorithm itself, but it should at least fix the exception. One other pointer is that if you are going to be processing lots of color values and performance is a concern you should really consider using image.LockBits instead of GetPixel. For more information on that see here: http://msdn.microsoft.com/en-us/library/5ey6h79d(v=vs.110).aspx.
It seems that 514 is bigger then your image actual Width. How did you come up with that number?

map maker application

I have created a somewhat complete application which allows me to create a map (.txt file with information about all the points of the map), load it and draw it.
My solution for this was, inside the windows forms application, to put a panel (since I need to be able to move on map) and inside that panel pictureboxes(since I want to put a background image and image on them) that represent points of map in size 50x50 pixels. The problem I am facing now is increased load time for my application, since I am loading pictures into the pictureboxes...
Does anyone have any alternative suggestion to what I have been attempting?
Visual representation might help:
The code, as requested: (well, some of it)
private void Load_Map()
{
for (int i = Y - 12; i < Y + 12; i++)
{
if ((i >= 0) & (i < Int32.Parse(MP.Mheight)))
{
string Line = xline[i];
for (int j = X - 12; j < X + 12; j++)
{
if ((j >= 0) & (j < Int32.Parse(MP.Mwidth)))
{
int X = i * Int32.Parse(MP.Mwidth) + j;
int Z = Int32.Parse(Line[j].ToString());
Map_Location[X] = Z;
Color H = new Color();
Map_Point(j, i, Map_Height(Z, H), 50);
}
}
}
}
}
Creating points:
private void Map_Point(int X, int Y, Color H, int Point_Size)
{
PictureBox MP = new PictureBox();
MP.Name = Map_Coordinates(X, Y);
MP.Size = new Size(Point_Size, Point_Size);
MP.Location = new Point(Y * (Point_Size + 1) + 4, X * (Point_Size + 1) + 4);
MP.BackColor = H;
Control MW = this.Controls["WorldMap"];
MW.Controls.Add(MP);
}
You'll be better off creating a custom control by deriving from System.Windows.Forms.Control and overriding the OnPaint method and doing your own drawing and handling click events yourself.
Using a large number of WinForms controls the way you're doing is an exercise in pain, as WinForms will create a hWnd object for each control, and WinForms doesn't scale too well, unfortunately.
You should be using System.Drawing.Graphics
Here are the MSDN Tutorials for it.
It has a method called DrawImage , which you can use instead of a picture box. For the grid you should be drawing it as a rectangle with a color for the background and vertical/horizontal lines to make the grid.

Trouble drawing 3d-style effect

I've been racking my brain trying to figure out how to animate an effect. This is related to a question I asked on math.stackexchange.com.
https://math.stackexchange.com/questions/91120/equal-division-of-rectangles-to-make-total/
As a side note, I didn't implement the drawing algorithm that was defined on the question above -- instead using my own in order to change the perspective to make it look more condensed.
I've been able to draw a stationary 3d style effect, but I am having trouble wrapping my brain around the logic to make the lines below look like they are coming towards you.
My code is as follows,
List<double> sizes = new List<double>();
private void Form1_Load(object sender, EventArgs e)
{
for (int y = 1; y < 10; y++)
{
double s = ((240 / 2) / y) / 4;
sizes.Add(s);
}
sizes.Add(0);
}
int offset = 0;
private void button1_Click(object sender, EventArgs e)
{
Bitmap b = new Bitmap(320, 480);
Graphics g = Graphics.FromImage(b);
Color firstColor = Color.DarkGray;
Color secondColor = Color.Gray;
Color c = firstColor;
int yOffset = 0;
for(int i = 0; i < sizes.Count; i++)
{
c = (i % 2 == 0) ? firstColor : secondColor;
int y = (int)Math.Round(b.Height - yOffset - sizes[i]);
int height = (int)Math.Round(sizes[i]);
g.FillRectangle(new SolidBrush(c), new Rectangle(0, y + offset, b.Width, height + offset));
yOffset += (int)sizes[i];
}
this.BackgroundImage = b;
offset+=1;
}
Each button click should cause the rectangles to resize and move closer. However, my rectangles aren't growing as they should. My logic draws fine, but simply doesn't work as far as moving goes.
So my question is:
Is there an existing algorithm for this effect that I am not aware of, or is this something pretty simple that I'm over thinking? Any help in correcting my logic or pointing me in the right direction would be very appreciated.
Interesting...
(video of the answer here: http://youtu.be/estq62yz7v0)
I would do it like that:
First, drop all RECTANGLE drawing and draw your effect line by line. Like so:
for (int y=start;y<end;y++)
{
color = DetermineColorFor(y-start);
DrawLine(left, y, right, y, color);
}
This is of course pseudo-code not to be troubled with GDI+ or something.
Everything is clear here, except on how to code DetermineColorFor() method. That method will have to return color of the line at specified PROJECTED height.
Now, on the picture, you have:
you point of view (X) - didn't know how to draw an eye
red line (that's your screen - projection plane)
your background (alternating stripes at the bottom)
and few projecting lines that should help you devise the DetermineColorFor() method
Hint - use triangle similarity to go from screen coordinates to 'bar' coordinates.
Next hint - when you are in 'bar' coordinates, use modulo operator to determine color.
I'll add more hints if needed, but it would be great if you solved this on your own.
I was somehow inspired by the question, and have created a code for the solution. Here it is:
int _offset = 0;
double period = 20.0;
private void timer1_Tick(object sender, EventArgs e)
{
for (int y = Height / 3; y < Height; y++)
{
using (Graphics g = CreateGraphics())
{
Pen p = new Pen(GetColorFor(y - Height / 3));
g.DrawLine(p, 0, y, Width, y);
p.Dispose();
}
}
_offset++;
}
private Color GetColorFor(int y)
{
double d = 10.0;
double h = 20.0;
double z = 0.0;
if (y != 0)
{
z = d * h / (double)y + _offset;
}
double l = 128 + 127 * Math.Sin(z * 2.0 * Math.PI / period);
return Color.FromArgb((int)l, (int)l, (int)l);
}
Experiment with:
d - distance from the eye to the projection screen
h - height of the eye from the 'bar'
period - stripe width on the 'bar'
I had a timer on the form and event properly hooked. Timer duration was 20ms.
Considering that you're talking here about 2D rendering, as much as I understodd, to me it seems that you're gonna to reenvent the wheel. Cause what you need, IMHO; is use Matrix Transformations already available in GDI+ for 2D rendering.
Example of aplying it in GDI+ : GDI+ and MatrixTranformations
For this they use System.Drawing.Drawing2D.Matrix class, which is inside Graphics.
The best ever 2D rendering framework I ever used is Piccolo2D framework which I used with great success in big real production project. Definitely use this for your 2D rendering projects, but first you need to study it little bit.
Hope this helps.

Categories