Android触摸屏幕实现类似光标的图片跟随

本文介绍了一种在屏幕上点击时出现指示光标的实现方法。通过自定义View并结合Canvas绘制,可在点击位置显示光标图片,抬起手指时光标消失。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

让点击的地方出现一个指示光标样式的图片

项目开发中遇到这样一个需求,在屏幕被点击的时候出现一个就像电脑光标一样的图片,指示你现在手指的焦点,本来想着用动画去实现,后来上网的时候看到了可以用画的方式实现,这样更灵活,下面是代码和思路。

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" />

这样就实现了当你点击屏幕的时候,在你点击的地方会出现一个提示光标了,当你抬起手指时,光标消失。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值