我通过在 svg 文件中绘制一个圆和三个动画线,使用 Java 制作了一个 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>
我该怎么做?作为计算的一部分,我需要哪些变量?我几乎在寻找一个公式来正确放置时间。
更新:Michael Lhomme 的回答给了我最好的图画
如何让时间进入圈内?他们非常接近,但我希望他们在里面。
谢谢!
最佳答案
你需要使用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 对齐属性 'text-anchor' 和 'alignment-baseline'
关于algorithm - 如何动态地将时间放置在时钟中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28131091/