这个用红、黄、绿三种颜色绘制红绿灯的代码是如何工作的



我在理解课本中这个例子的概念时遇到了很多困难。这个想法是用红、黄、绿三种颜色画一个红绿灯。我有几个问题。我很难弄清楚代码的哪一部分起什么作用。

  1. 我认为cxcy是用来计算页面中心的,对吗
  2. fxfy是否要计算出帧的中心
  3. 我不知道dy是做什么的,也不知道为什么它被4而不是3除以3,LAMP_RADIUS完全让我困惑
  4. 在红色、黄色和绿色的所有三个add(createFilledCircle)上,我不明白它们在红绿灯框架内的位置是如何计算的
  5. 在方法createFilledCircle()中,我不理解GOval circle = newGOval(x-r, y-r, 2 * r, 2 * r);。我不明白x-ry-r是做什么的,以及这和位置有什么关系
import acm. graphics.*;
import acm. program.*;
import java.awt.*;
public class DrawStoplight extends GraphicsProgram {
public void run () {
double cx = getWidth() / 2;
double cy = getHeight() / 2; 
double fx = cx - FRAME_WIDTH / 2; 
double fy = cy- FRAME_HEIGHT / 2; 
double dy = FRAME_HEIGHT / 4 + LAMP_RADIUS / 2; 
GRect frame = new GRect(fx, fy, FRAME_WIDTH, FRAME_HEIGHT);
frame.setFilled(true);
frame.setColor(Color.GRAY);
add(frame);
add(createFilledCircle(cx, cy - dy, LAMP_RADIUS, Color.RED));
add(createFilledCircle(cx, cy, LAMP_RADIUS, Color.YELLOW));
add(createFilledCircle(cx, cy + dy, LAMP_RADIUS, Color.GREEN));
}
private GOval createFilledCircle(double x, double y, double r, Color color){
GOval circle = new GOval(x-r, y-r, 2 * r, 2 * r)
circle.setColor(color);
circle.setFilled(true);
return circle;
}
private static final double FRAME_WIDTH = 50; 
private static final double FRAME_HEIGHT = 100; 
private static final double LAMP_RADIUS = 10; 
}
1. Am I right to assume cx and cy are to figure out the center of the page?

2. Are fx and fy to figure out the center of the frame?

不完全是。他们正在计算框架的左上角。它们从中心开始,在每个方向上"后退"一半的帧大小。

3. I don't know what dy does and why it's divided by 4 and not 3 for 3 lights and the LAMP_RADIUS totally confuses me. 

往下看代码。dy是灯之间的垂直距离。黄灯正好画在中心,红色是上面的dy,绿色是下面的dy。除数是4,因为作者选择将红光的底边与距离帧顶部的帧高度的1/4点对齐。类似地,他选择将绿光的顶部与距底部帧高度的1/4点对齐。他本可以选择许多其他计算CCD_ 16的方法。

4. On all three add(createFilledCircle) for red, yellow and green I don't understand how their position is calculated inside the stoplight frame. 

它们都有相同的x坐标:框架的中心。y坐标的计算如3中所述。请记住,在屏幕坐标中,正方向是向下的,所以增加y会使光线降低。降低会使其更高。

5. In the method createFilledCircle() I don't understand GOval circle = newGOval(x-r, y-r, 2 * r, 2 * r);. I don't understand what x-r and y-r does and how that relates to position.

请阅读newGOval的手册定义。它把一个椭圆形刻在一个长方形里面。参数是矩形的左上角,后面跟着宽度和高度。因此,如果(x,y)是中心,这给出了一个对角线为(x-r,y-r)到(x+r,y+r)的方框。当你在上面刻一个椭圆时,你会得到一个以(x,y)为中心的圆。

我认为cxcy是计算页面中心的对吗?

fxfy能算出帧的中心吗?

不,它们是左上角坐标

我不知道dy是做什么的,也不知道为什么它被4而不是3除以3,LAMP_RADIUS完全让我困惑。

要在一个框内垂直放置三个灯,需要一个在中间,一个在1/4高度,一个位于3/4高度,因此需要除以四。我不确定LAMP_RADIUS为什么会出现在其中。它似乎是我通常所说的"模糊因素",以使灯的间距更大,即一个看起来正确的图形,但没有任何充分的理由为什么它看起来正确。。。

在红色、黄色和绿色的所有三个add(createFilledCircle)上,我不明白它们在红绿灯框架内的位置是如何计算的。

它们只是由dy垂直隔开

在方法createFilledCircle()中,我不理解GOval circle = newGOval(x-r, y-r, 2 * r, 2 * r);。我不明白x-ry-r是做什么的,以及这和位置有什么关系。

GOval在坐标(x - r, y - r)定义的框内放置一个圆圈,尺寸为2r,即以(x, y)为中心的边长为2r的正方形

最新更新