1
我想中心一个现有的三角形。提示要求三角形的底部是画布的长度,并且峰顶接触顶部和居中。这是一个班级,代码给了。如何在Java中居中图像?
public class Triangle {
private int height;
private int width;
private int xPosition;
private int yPosition;
private String color;
private boolean isVisible;
public Triangle() {
height = 270;
width = 270;
xPosition = 120;
yPosition = 120;
color = "green";
isVisible = false;
}
public void makeVisible() {
isVisible = true;
draw();
}
public void makeInvisible() {
erase();
isVisible = false;
}
public void moveRight() {
moveHorizontal(20);
}
public void moveLeft() {
moveHorizontal(-20);
}
public void moveUp() {
moveVertical(-20);
}
public void moveDown() {
moveVertical(20);
}
public void moveHorizontal(int distance) {
erase();
xPosition += distance;
draw();
}
public void moveVertical(int distance) {
erase();
yPosition += distance;
draw();
}
public void slowMoveHorizontal(int distance) {
int delta;
if(distance < 0) {
delta = -1;
distance = -distance;
}
else {
delta = 1;
}
for(int i = 0; i < distance; i++) {
xPosition += delta;
draw();
}
}
public void slowMoveVertical(int distance) {
int delta;
if(distance < 0) {
delta = -1;
distance = -distance;
}
else {
delta = 1;
}
for(int i = 0; i < distance; i++) {
yPosition += delta;
draw();
}
}
public void changeSize(int newHeight, int newWidth) {
erase();
height = newHeight;
width = newWidth;
draw();
}
public void changeColor(String newColor) {
color = newColor;
draw();
}
private void draw() {
if(isVisible) {
Canvas canvas = Canvas.getCanvas();
int[] xpoints = { xPosition, xPosition + (width/2), xPosition + width };
int[] ypoints = { yPosition + height, yPosition, yPosition + height};
canvas.draw(this, color, new Polygon(xpoints, ypoints, 3));
canvas.wait(10);
}
}
private void erase() {
if(isVisible) {
Canvas canvas = Canvas.getCanvas();
canvas.erase(this);
}
}
}
嗨,欢迎来到堆栈溢出。 请不要要求你的作业的解决方案,尝试自己找一个好方法,以成为一个更好的开发者;-) –
删除多余的评论 – stealthjong