[英]Java Android App Random Color and Timer
我有一個帶有正方形的應用程序,該正方形每1.5秒在屏幕上移動一次,每次單擊它都會得到一個積分。 我正在嘗試使每次單擊正方形的顏色都變為隨機顏色。 另外,我想在設置下選擇一個更硬的模式,其中正方形每0.7秒移動一次。
這是我的繪畫方法:
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLUE);
Paint dotPaint = new Paint();
canvas.drawRect(dotX, dotY, dotX + 60, dotY + 60, dotPaint);
dotPaint.setColor(Color.WHITE);
dotPaint.setTextSize(60);
canvas.drawText("Score: " + score, 20, 60, dotPaint);
這是我的onTouch方法:
public boolean onTouch(View v, MotionEvent event) {
if (detectHit( (int)event.getX(), (int)event.getY() )) {
score++;
invalidate();
}
return false;
我不太確定如何在每次單擊時更改正方形的顏色。
Also, here is my menu items:
public boolean onOptionsItemSelected(MenuItem item) {
// handle menu item selection
switch (item.getItemId()){
case R.id.item1:
newGame();
return true;
case R.id.item2:
quit();
return true;
case R.id.item3:
harder();
return true;
default:
return super.onOptionsItemSelected(item);
and my harder method:
public void harder(){
timer.schedule(task, 0, 700);
}
好吧,只是一個建議,將您的detectHits()方法從(int ...,int ...)更改為(MotionEvent ...)可以縮短通話時間。
對於隨機顏色,您將不得不以編程方式生成一種顏色。 您可能想使用此Color.rgb(int red, int green, int blue)
方法。
所以現在您要做的是,生成Random int以生成Color,就像這樣
Random rnd = new Random();
Color rndCol = Color.rgb(rnd.nextInt(254), rnd.nextInt(254), rnd.nextInt(254));
現在您將擁有該顏色。 首先,它不鼓勵在onDraw期間分配對象,因此將Paint的分配移動到onCreate / onResume並將其作為過程中的一個字段。 然后,您將必須像這樣調整您的onTouchMethod。
public boolean onTouch(View v, MotionEvent event) {
if (detectHit(event)) {
changeColor();
score++;
invalidate();
}
return false;
private void changeColor(){
Random rnd = new Random();
Color rndCol = Color.rgb(rnd.nextInt(254), rnd.nextInt(254), rnd.nextInt(254));
dotPaint.setColor(rndCol); // this should be a field by now and accessible from within this method
}
在將速度從1.5更改為0.7的過程中,將計時作為類中的一個字段,並在某個點減小此值以減少計時器。
正如您沒有顯示您當前如何每1.5秒移動一次方塊,我無法為您修改代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.