问题是我希望保留矩形的大小,同时它在画布中来回移动。这是myview.java代码:
public class MyView extends View {
private int xMin = 0;
private int xMax;
private int yMin = 0;
private int yMax;
private float rectX =130;
private float rectY =180;
private float rectSpeedX = 5;
private float rectSpeedY = 3;
private RectF RectBounds;
private Paint paint;
public MyView(Context context) {
super(context);
RectBounds = new RectF();
paint = new Paint();
}
@Override
public void onDraw(Canvas canvas) {
RectBounds.set(rectX, rectX, rectY, rectY);
paint.setColor(Color.BLACK);
paint.setStrokeWidth(3);
canvas.drawRect(RectBounds,paint);
paint.setStrokeWidth(0);
paint.setColor(Color.CYAN);
canvas.drawRect(RectBounds,paint);
paint.setColor(Color.YELLOW);
canvas.drawRect(RectBounds,paint);
start();
invalidate();
}
private void start() {
rectX += rectSpeedX;
rectY += rectSpeedY;
if (rectX> xMax) {
rectSpeedX = -rectSpeedX;
rectX = xMax;
} else if (rectX < xMin) {
rectSpeedX = -rectSpeedX;
rectX = xMin;
}
if (rectY > yMax) {
rectSpeedY = -rectSpeedY;
rectY = yMax;
} else if (rectY < yMin) {
rectSpeedY = -rectSpeedY;
rectY = yMin;
}
}
@Override
public void onSizeChanged(int w, int h, int oldW, int oldH) {
xMax = w-1;
yMax = h-1;
}
}
此外,如果您有任何建议可以缩短我的代码。我会很高兴的。谢谢。
答案 0 :(得分:0)
你可以使用类似的东西:
RectBounds.set(rectX, rectX + rectWidth, rectY, rectY + rectHeight);
你也不应该使用大写字母表示对象名称(RectBounds - &gt; rectBounds),或者对于这种特殊情况,你应该将它命名为'rect',因为它是一个RectF。