I am attempting to move a picture box around a circle at the center of my form. I am having an issue accurately depicting where the picture box should appear due to rounding issues. A subset of my data may reflect the following:
109.023696905025,151.715396359085
109.041149311463,152.715244054241
109.0586017179,153.715091749398
109.076054124337,154.714939444554
109.093506530774,155.714787139711
109.110958937212,156.714634834867
109.128411343649,157.714482530023
109.145863750086,158.71433022518
A control's Location
field only accepts Point
, which truncates my points decimal places, resulting in a hexegon-like shape when drawn. I am using the following code block to create my coordinates:
double x1 = pictureBox1.Location.X;
double y1 = pictureBox1.Location.Y;
double cx = (double)this.Width / 2;
double cy = (double)this.Height / 2;
double radius = Math.Sqrt(Math.Pow(cx - x1, 2) + Math.Pow(cy - y1, 2));
double arc = Math.Atan((y1 - cy) / (x1 - cx));
double x = cx + radius * Math.Cos(arc + Math.PI - (Math.PI / 180.0));
double y = cy + radius * Math.Sin(arc + Math.PI - (Math.PI / 180.0));
Given the inaccuracy when creating a Point
object, and x, and y, representing my points, how can I accurately draw the points generated by my code to be more accurate?
Console.WriteLine("{0},{1}",x, y);
pictureBox1.Location = new Point((int)x, (int)y); // Only takes integers, which results in the irregular path.
First of all, by typecasting the doubles as int's you are automatically truncating their values. A number like 23.999 will automatically be truncated to 23 when in fact it is closer to 24. It would be better to round to the nearest integer instead of truncating.
Second, there is no way around the fact that pixels on a screen occur in discrete steps. Screens locations are not continuous and are therefore incapable of truly showing a decimal value. However, you can do a better job of approximating a decimal value by using an anti-aliasing technique. In such a technique you may draw two or more dots next to each other with differing magnitudes that are meant to represent one point. For example, I might plot the number 36.75 as a stronger pixel at location 36 with a weaker pixel at location 35. The resulting effect is a "point" that appears to be somewhere between location 35 and 36 but closer to 36. Google for anti-aliasing to get more info.