I’m trying to create a drawing on a Windows Form that will simulate what I was trying to do with a ProgressBar used as a health bar. I didn’t like the ProgressBar because it would animate a fill at the start when I set the Value equal to the Maximum.
This is my method
private void Battlefield_Paint(object sender, PaintEventArgs e)
{
using (SolidBrush blackBrush = new SolidBrush(Color.Black))
using (SolidBrush redBrush = new SolidBrush(Color.Red))
using (Graphics formGraphics = this.CreateGraphics())
{
formGraphics.FillRectangle(blackBrush, new Rectangle(12, 12, 76, 23));
formGraphics.FillRectangle(redBrush, new Rectangle(14, 14, 72*(p1.CurrentHealth/p1.MaxHealth), 19));
int result = 72 * (p1.CurrentHealth / p1.MaxHealth);
Console.WriteLine(result);
}
}
I have a timer redrawing the form every 50ms.
I am having a problem where the red rectangle inside the black rectangle will draw fine at first, but once my character takes damage, and CurrentHealth is less than MaxHealth, the result of 72*(p1.CurrentHealth/p1.MaxHealth) comes back as 0, and the rectangle doesn’t even show up on the screen, as I think it’s being drawn with 0 width…
I don’t know what is going wrong with this calculation that would make it return 0. I’ve ran it thru the debugger a bunch and the values going in look correct, 30 and 30 for both at first, then something like 28, 30 the next time thru, and I get a value of 0…
I suppose that
CurrentHealthandMaxHealthare integers and that you are doing integer division, when you divide 6 with 10 you get 0, instead of 0.6You should try this:
Also you should use
e.Graphicsinstead of making newGraphicsobject every time.