Android實現(xiàn)隨手指移動小球
更新時間:2020年08月24日 09:24:43 作者:Gorky_19
這篇文章主要為大家詳細介紹了Android實現(xiàn)隨手指移動小球,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了Android實現(xiàn)隨手指移動小球的具體代碼,供大家參考,具體內(nèi)容如下
這個隨手指移動小球,首先要使用paint畫筆在canvas畫布畫出一個圓,然后重寫OnTouchEvent(),進行小球的坐標的獲取和小球的重新繪畫。
package com.bwei.self_view; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; /** * Created by ZhangTAO on 2017/11/2. */ public class MyView extends View{ // 初始化圓的位置 public int x = 200; public int y = 600; Context context; public MyView(Context context) { super(context,null); this.context = context; } public MyView(Context context, @Nullable AttributeSet attrs) { super(context, attrs,0); this.context = context; } public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(); this.context = context; } private void initView() { setBackgroundColor(Color.BLUE); } /** * @canvas 畫布 paint 畫筆 */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //建立一根畫筆 Paint paint = new Paint(); paint.setStyle(Paint.Style.FILL); paint.setColor(Color.RED); paint.setFakeBoldText(true); //畫布 canvas.drawCircle(DipUtils.dip(getContext(),x), DipUtils.dip(getContext(),y), DipUtils.dip(getContext(),50),paint); } /** * 進行設置touch移動 */ @Override public boolean onTouchEvent(MotionEvent event) { super.onTouchEvent(event); int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN : case MotionEvent.ACTION_MOVE : case MotionEvent.ACTION_UP : //獲取當前觸摸點的x,y坐標 x = (int) event.getX(); y = (int) event.getY(); invalidate(); break; } // 獲取屏幕的寬高 WindowManager manger = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); int width = manger.getDefaultDisplay().getWidth(); int height = manger.getDefaultDisplay().getHeight(); //重新繪制圓 ,控制小球不會被移除屏幕 if(x>=20 && y>=20 && x<=width-20 && y<height-20) { invalidate(); } //自己處理觸摸事件 return true; //修改當前的坐標 // this.x =(int) event.getX(); // this.y =(int) event.getY(); //重繪小球 // this.invalidate(); // return true; } }
效果圖:
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Android?RecyclerChart其它圖表繪制示例詳解
這篇文章主要為大家介紹了Android?RecyclerChart其它圖表繪制示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12詳解Android開發(fā)技巧之PagerAdapter實現(xiàn)類的封裝
這篇文章主要介紹了詳解Android開發(fā)技巧之PagerAdapter實現(xiàn)類的封裝,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11Android使用TransitionDrawable漸變切換多張圖片
這篇文章主要為大家詳細介紹了Android使用TransitionDrawable漸變切換多張圖片,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-08-08Android 判斷SIM卡屬于哪個移動運營商的實現(xiàn)代碼
有時候我們需要在Android中獲取本機網(wǎng)絡提供商呢,這里簡單分享下,方便需要的朋友2013-05-05