這篇文章主要介紹了Android如何實現自定義view圓并隨手指移動,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
網站建設哪家好,找創新互聯!專注于網頁設計、網站建設、微信開發、小程序設計、集團企業網站建設等服務項目。為回饋新老客戶創新互聯還提供了豐縣免費建站歡迎大家使用!
具體內容如下
main代碼
public class MainActivity extends AppCompatActivity { private int screenW; //屏幕寬度 private int screenH; //屏幕高度 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); 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 MyView(this)); } //自定義繪圖類 class MyView extends View { private Paint paint; //定義畫筆 private float cx = 50; //圓點默認X坐標 private float cy = 50; //圓點默認Y坐標 private int radius = 20; //定義顏色數組 private int colorArray[] = {Color.BLACK,Color.BLACK,Color.GREEN,Color.YELLOW, Color.RED}; private int paintColor = colorArray[0]; //定義畫筆默認顏色 public MyView(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(); //隨機設置畫筆顏色 setPaintRandomColor(); //繪制小圓作為小球 canvas.drawCircle(cx, cy, radius, paint); } //為畫筆設置隨機顏色 private void setPaintRandomColor(){ 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_UP: // 抬起 cx = (int) event.getX(); cy = (int) event.getY(); // 通知重繪 postInvalidate(); break; } /* * 備注1:此處一定要將return super.onTouchEvent(event)修改為return true,原因是: * 1)父類的onTouchEvent(event)方法可能沒有做任何處理,但是返回了false。 * 2)一旦返回false,在該方法中再也不會收到MotionEvent.ACTION_MOVE及MotionEvent.ACTION_UP事件。 */ //return super.onTouchEvent(event); return true; } } }
布局
感謝你能夠認真閱讀完這篇文章,希望小編分享的“Android如何實現自定義view圓并隨手指移動”這篇文章對大家有幫助,同時也希望大家多多支持創新互聯,關注創新互聯行業資訊頻道,更多相關知識等著你來學習!