Reputation:
I'm trying to draw line over all circle surface, my current shape look like:
My wrong attempt:
for (int i = 0; i < 24; i++) {
g.drawLine(xCenter - clockRadius + i , yCenter - clockRadius + i, xCenter - clockRadius + i + 5,
yCenter - clockRadius + i + 5);
}
I'm trying to draw a full clock :
Upvotes: 1
Views: 363
Reputation:
You need to calculate points over 360 degree not just 24, so you have the radius and angel rotation (angel rotation from 0 to 360) to get the proper point of (x,y) we need to multiply sin or cos of angel with radius.
for (int i = 0; i < 360; i++) {
int x = (int) (clockRadius * Math.cos(i)) + xCenter;
int y = (int) (clockRadius * Math.sin(i)) + yCenter;
g.drawLine(x, y, x + 5, y + 5);
}
Note: for better result you may need to develop two loops, one for right (180) part and another for left (180) part.
Edit: to get the right direction you need to check for angel e.g:
int xV = 0, yV = 0;
if (i <= 90){
xV = 5;
yV = 5;
}
Upvotes: 0
Reputation: 80127
I suspect that you want to draw small segments - ticks, centered at circumference and directed from the circle center. In this case use trigonometry alike hour hands drawing.
for (int i = 0; i < 24; i++) {
double ang = i * Math.Pi / 12;
g.drawLine((int) (xCenter + (clockRadius - 5) * Math.Cos(ang)),
(int) (yCenter + (clockRadius - 5) * Math.Sin(ang)),
(int) (xCenter + (clockRadius + 5) * Math.Cos(ang)),
(int) (yCenter + (clockRadius + 5) * Math.Sin(ang)));
}
Upvotes: 1
Reputation: 8598
You are looking for cosinus and sinus.
Your clock is a circle, and you can easily translate your steps into degrees on that circle. If you want to have 24 steps, 12 would be 180° (or π) and 24 would be 360°, or 2π. So to get the correct angles for each index, just devide 2π (360°) by 24 and multiply it by the current index. Then feed that resulting angle to the cos and sin functions, which give you the x and y coordinates respectively:
double x = Math.cos(2 * Math.PI / 24 * i);
double y = Math.sin(2 * Math.PI / 24 * i);
Of course you can optimize the 2 and the 24 into one constant that you define somewhere and then use in your code.
Upvotes: 3