package com.bwie.playbass;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private int screenW;//屏幕寬度
private int screenH;//屏幕高度
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
Display dis=this.getWindowManager().getDefaultDisplay();
//設置全屏
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
//獲取屏幕寬度
screenW=dis.getWidth();
//獲取屏幕高度
screenH=dis.getHeight();
setContentView(new BallView(this));
}
class BallView extends View{
//定義畫筆
private Paint paint;
//圓點默認X座標
private float cx=50;
//圓點默認Y座標
private float cy=50;
//定義半徑
private int radius=100;
//定義畫筆顏色
private int colorArray[] ={Color.BLACK,Color.GREEN,Color.YELLOW,Color.RED};
private int paintColor = colorArray[0];
public BallView(Context context) {
super(context);
//初始化畫筆
initPaint();
}
private void initPaint() {
paint=new Paint();
paint.setAntiAlias(true);
paint.setColor(paintColor);
}
//重寫onDraw方法
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//將屏幕設置爲白色
canvas.drawColor(Color.WHITE);
//修正圓點座標
revise();
//隨機設置畫筆顏色
setPainRandomColor();
//繪製小圓作爲小球
canvas.drawCircle(cx,cy,radius,paint);
}
//爲畫筆設置隨機顏色
private void setPainRandomColor() {
Random rand=new Random();
int randomIndex = rand.nextInt(colorArray.length);
paint.setColor(colorArray[randomIndex]);
}
//修正圓點座標
private void revise() {
if(cx <= radius){
cx = radius;
}else if(cx >= (screenW-radius)){
cx=screenW-radius;
}
if(cy <= radius){
cy=radius;
}else if(cy >= (screenH-radius)){
cy=screenH-radius;
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch(event.getAction()){
//按下
case MotionEvent.ACTION_DOWN:
cx = (int) event.getX();
cy = (int) event.getY();
// 通知重繪
postInvalidate();//該方法會調用onDraw方法,重新繪圖
break;
//移動
case MotionEvent.ACTION_MOVE:
cx=(int)event.getX();
cy=(int)event.getY();
postInvalidate();
break;
//擡起
case MotionEvent.ACTION_POINTER_UP:
cx=(int)event.getX();
cy=(int)event.getY();
postInvalidate();
break;
}
return true;
}
}
}
圓形隨手指移動
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.