我使用Java制作了一个svg时钟,将一个圆圈和三个动画线条绘制成一个svg文件。这就是我的时钟的样子。
现在我想将时间添加到时钟中,如下所示。
如何根据圈子的cx
,cy
,r
和stroke-width
进行计算?我希望用户提供这些值,然后我绘制其余部分,包括小时,分钟和秒针。我并不担心时钟指针,我可以解决这个问题,但我不确定如何动态地将时间放在时钟上。我不想手动放置它们。
这是我的SVG文件。
<svg xmlns = 'http://www.w3.org/2000/svg' version = '1.1' width="500.0" height="500.0">
<circle cx="100.0" cy="100.0" r="50.0" stroke="none" stroke-width="1.0" fill="rgba(102,205,170,0.4)"/>
<line x1="100" y1="100" x2="100" y2="62" stroke="red" stroke-width="2.0" stroke-linecap="round">
<animateTransform attributeName="transform" type="rotate" from="0 100 100" to="360 100 100" dur="500ms" repeatCount="indefinite"></animateTransform>
</line>
<line x1="100" y1="100" x2="100" y2="62" stroke="black" stroke-width="2.0" stroke-linecap="round">
<animateTransform attributeName="transform" type="rotate" from="0 100 100" to="360 100 100" dur="3s" repeatCount="indefinite"></animateTransform>
</line>
<line x1="100" y1="100" x2="100" y2="75" stroke="black" stroke-width="4.0" stroke-linecap="round">
<animateTransform attributeName="transform" type="rotate" from="0 100 100" to="360 100 100" dur="40s" repeatCount="indefinite"></animateTransform>
</line>
</svg>
我该怎么做以及计算过程中需要哪些变量?我正在寻找一个公式,以便正确地安排时间。
更新:MichaëlLhomme的回答给了我最好的图纸
如何让时间进入圈内?它们非常接近,但我希望它们在里面。
谢谢!
答案 0 :(得分:2)
您需要使用 cos 和 sin 函数来计算圆上每个点的坐标:
/*
* @param radius The clock radius
* @param cx X coordinates of the clock's center
* @param cy Y coordinates of the clock's center
*/
void drawHours(int radius, int cx, int cy) {
for(int i = 1; i <= 12; i++) {
double x = radius * Math.cos(Math.PI / -2 + (2 * i * Math.PI) / 12) + cx
double y = radius * Math.sin(Math.PI / -2 + (2 * i * Math.PI) / 12) + cy
String text = Integer.toString(i);
//draw text at [x, y] using style 'text-anchor' set to 'middle' and 'alignment-baseline' set to 'middle'
}
}
要调整文本的位置,请使用svg alignment属性&#39; text-anchor&#39;和&#39; alignment-baseline&#39;
答案 1 :(得分:1)
从圆圈的中心开始,使用sin
和cos
三角函数计算您将在何时显示一小时的给定数字的点的中心。
要计算每个数字的中心点,这样的事情可能会起作用(未经测试):
// This will calculate the center point for the location at which a
// label for the given hour should be:
Point2D.Double getHourLocation(int hour, int clockDiameter)
{
double radians;
double x;
double y;
// assume 360 degrees, so range needs to be 0..360:
// first, adjust hour so 0 is at the top, 15s is at 3 o'clock, etc
// 360/12 = 30, so
hour *= 30;
// calculate x, y angle points relative to center
radians = Math.toRadians(hour * Math.PI / 180);
x = Math.cos(radians);
y = Math.sin(radians);
// sin() and cos() will be between -1.0 and 1.0 so adjust for that
x *= 100;
y *= 100;
// x, y points should now be relative to center of clock
x += clockDiameter;
y += clockDiameter;
return new Point2D.Double(x, y);
}
计算完这个位置后,您必须调整字体特征。例如,假设您知道“12”文本应居中于(-50,50) - 您需要调整x,y坐标以考虑文本宽度和高度,以确定实际开始绘制的位置