1
對於我的Pong克隆,我試圖在類GamePanel的類視圖中繪製一個自定義的類視圖。然而,它在運行時並沒有在屏幕上看到。如何在視圖上繪製自定義視圖(例如圓形)?
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);
}
我打過電話無效()和postInvalidate()我MainThread線程內,在的GamePanel的構造和球的構造。球從未被吸引到屏幕上。
正如你所看到的,我已經遇到了Pong槳的問題,因此我在GamePanel中創建了兩個非常難看的Rectangles。
如何封裝矩形和圓形(球),以便它仍然可以繪製在畫布上?
非常感謝您的回答。我瞭解你的方法。一個問題:如果我想添加多個自定義視圖並在GamePanel中繪製它們,該怎麼辦?所以我的意思是,如果我也將矩形封裝到像Ball這樣的自己的類中?我會讓GamePanel從ViewGroup擴展還是佈局類型並將自定義視圖添加到那裏? –
讓我列舉案例。如果您不打算移動這些形狀,那麼最好將GamePanel擴展到ViewGroup,並將其創建爲獨立視圖,就像創建「球」並將這些視圖添加到GmePanel一樣。但是,如果您要將諸如矩形和圓形等形狀動態地移動或移動到GamePanel中的任何位置,則最好將其功能移到另一個類(不單獨的視圖)中並在GamePanel中進行初始化。看到這個項目庫,例如https://github.com/81813780/AVLoadingIndicatorView –
好吧,我明白了。如你所知,我已經將球分成了一個單獨的班級。我不能將它們放到ViewGroup中,因爲它們需要動態。哪個類現在需要延長,我在哪裏初始化它在GamePanel /我在哪裏告訴它在GamePanel中繪製球?不好意思問這麼多基本的東西。我是Android開發新手,我一直在尋找如何封裝矩形和球幾天。這似乎很簡單,但我無法想象它。感謝你幫助我 –