Android觸摸屏幕實現類似光標的圖片跟隨

讓點擊的地方出現一個指示光標樣式的圖片

項目開發中遇到這樣一個需求,在屏幕被點擊的時候出現一個就像電腦光標一樣的圖片,指示你現在手指的焦點,本來想着用動畫去實現,後來上網的時候看到了可以用畫的方式實現,這樣更靈活,下面是代碼和思路。

1.自定義一個View

public class LockScreenView extends ImageView {
   public float currentX = 40;
   public float currentY = 50;
   private Bitmap bmp;

   public LockScreenView(Context context) {
       super(context);
       init();
   }

   public LockScreenView(Context context, AttributeSet attrs) {
       super(context, attrs);
       init();
   }

   public LockScreenView(Context context, AttributeSet attrs, int defStyleAttr) {
       super(context, attrs, defStyleAttr);
       init();
   }

//初始化你需要顯示的光標樣式
   private void init() {

       if (bmp == null) {
           bmp = BitmapFactory.decodeResource(getResources(), R.drawable.lockscreen_x);
       }
   }

   private boolean isClickView = false;//標識是否是人爲點擊,是則爲true

   @Override
   public void onDraw(Canvas canvas) {
       super.onDraw(canvas);
       if (isClickView == true && bmp != null) {
           //創建畫筆
           Paint p = new Paint();
           canvas.drawBitmap(bmp, currentX - (bmp.getWidth() / 2), currentY - (bmp.getHeight() / 2), p);
          isClickView = false;
       }
   }

   @Override
   public boolean onTouchEvent(MotionEvent event) {
       //當前組件的currentX、currentY兩個屬性
       this.currentX = event.getX();
       this.currentY = event.getY();
       isClickView = true;

       if (event.getAction() == MotionEvent.ACTION_UP && bmp != null) {
           this.currentX = -bmp.getWidth();
           this.currentY = -bmp.getHeight();
           isClickView = false;
       }
       //通知改組件重繪
       this.invalidate();
       //返回true表明處理方法已經處理該事件
       return true;
   }
}

2.在xml佈局文件中引用
寫好了自定義的view後只需要在你的xml文件中的view引用就可以了

<com.thunder.ktv.module.main.view.LockScreenView
    android:id="@+id/lockScreenView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

這樣就實現了當你點擊屏幕的時候,在你點擊的地方會出現一個提示光標了,當你擡起手指時,光標消失。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章