对于我的Pong克隆,我试图将类Ball中的自定义视图绘制到GamePanel类中的View上。 但是在运行时屏幕上无处可见。
public class Ball extends View {
private float posX;
private float posY;
private float radius;
private Paint paint;
public Ball(Context context, float posX, float posY, float radius){
super(context);
this.posX = posX;
this.posY = posY;
this.radius = radius;
setWillNotDraw(false);
init();
}
private void init(){
paint = new Paint();
paint.setColor(Color.WHITE);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawCircle(posX, posY, radius, paint);
}
现在这是我的GamePanel类。
public class GamePanel extends View implements GestureDetector.OnGestureListener{
private Context context;
//Screen height and width in pixels
private static int width;
private static int height;
private MainThread thread;
private Rect paddle1;
private Rect paddle2;
private Ball ball;
private Paint paint;
//Starting position paddle1
private int xPos1;
private int yPos1;
// Starting position paddle2
private int xPos2;
private int yPos2;
//Width and height of paddles
private int pWidth;
private int pHeight;
private GestureDetectorCompat gestureDetector;
public GamePanel(Context context) {
super(context);
this.context = context;
//Information we will need for positioning our objects inside the panel
DisplayMetrics displayMetrics = Resources.getSystem().getDisplayMetrics();
width = displayMetrics.widthPixels;
height = displayMetrics.heightPixels;
//Make the GamePanel focusable
setFocusable(true);
// Thread needs information about the game panel
thread = new MainThread(this);
pWidth = 100;
pHeight = height/2;
xPos1 = width/15;
yPos1 = 0;
xPos2 = width - xPos1 - pWidth;
yPos1 = 0;
paddle1 = new Rect(xPos1, yPos1, xPos1 + pWidth, yPos1 + pHeight);
paddle2 = new Rect(xPos2, yPos2, xPos2 + pWidth, yPos2 + pHeight);
paint = new Paint();
paint.setColor(Color.WHITE);
ball = new Ball(context, 300, 300, 300);
setBackgroundColor(Color.BLACK);
this.gestureDetector = new GestureDetectorCompat(context, this);
thread.setRunning(true);
thread.start();
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawRect(paddle1, paint);
canvas.drawRect(paddle2, paint);
}
我尝试在我的MainThread线程中,在GamePanel的构造函数和Ball的构造函数中调用invalidate()和postInvalidate()。球永远不会被吸引到屏幕上。
正如你所看到的,我已经在Pong中遇到了这个问题,因此我在GamePanel中创建了两个非常难看的矩形。
如何封装矩形和圆圈(球)以便仍然可以在画布上绘制?
答案 0 :(得分:4)
您正在 GamePanel 视图中创建球(圆圈)视图。仅仅因为你创建的视图并不意味着它将在屏幕上绘制。您需要将视图附加到布局。 简单的解决方案是将 GamePanel 扩展为 Ball
public class GamePanel extends Ball {
}
然后在GamePanel
添加super.onDraw();
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(); //Will draw the circle before drawing rectangle
canvas.drawRect(paddle1, paint);
canvas.drawRect(paddle2, paint);
}
如果您将super.onDraw()
放在drawRect
下方,则绘制矩形后将绘制圆圈。
您还需要了解添加视图的基本概念 布局。