让点击的地方出现一个指示光标样式的图片
项目开发中遇到这样一个需求,在屏幕被点击的时候出现一个就像电脑光标一样的图片,指示你现在手指的焦点,本来想着用动画去实现,后来上网的时候看到了可以用画的方式实现,这样更灵活,下面是代码和思路。
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" />
这样就实现了当你点击屏幕的时候,在你点击的地方会出现一个提示光标了,当你抬起手指时,光标消失。