我想将现有三角形居中。提示要求三角形的底边为 Canvas 的长度,顶点接触顶部并居中。这是一个类,并且给出了代码。
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);
}
}
}
最佳答案
三角形的中心位于
xPosition + (width / 2)
yPosition + (height / 2)
要“居中”,您需要移动水平/移动垂直,直到三角形的中心位于要居中的空间的中心
关于java - Java中如何使图像居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42281441/