public class TurnTableView extends View {
private int mHeight;
private int mWidth;
private int x;
private int y;
private boolean mOnBall;
private int mRadius = 90;
public TurnTableView(Context context) {
this(context,null);
}
public TurnTableView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public TurnTableView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override//测量
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//获取当前控件的宽高
mWidth = this.getWidth();
mHeight = this.getHeight();
//获取屏幕的正中心点
x = mWidth / 2;
y = mHeight / 2;
}
@Override//绘制
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();//画笔
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);//设置图片
canvas.drawBitmap(bitmap,x,y,paint);//放入图片
}
//手势监听器,可以得到用户手指在屏幕上滑动的坐标
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
float newX = event.getX();
float newY = event.getY();
//进行判断,判断用户的手指是否按在了图上
mOnBall = isOnBall(newX,newY);
Toast.makeText(getContext(), "用户的手指是否点到图上了吗?"+mOnBall, Toast.LENGTH_SHORT).show();
break;
case MotionEvent.ACTION_MOVE:
//只用用户点到图上时,我才让它动
if (mOnBall){
x = (int) event.getX();
y = (int) event.getY();
//回调OnDrawer方法
postInvalidate();
}
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
//,判断用户的手指是否按在了图上
private boolean isOnBall(float newX, float newY) {
//勾股定理的绝对值
double sqrt = Math.sqrt((newX - x) * (newX - x) + (newY - y) * (newY - y));
//判断绝对值是否小于等于半径
if(sqrt <= mRadius){
return true;
}
return false;
}
}
自定义View 手指拖动图片移动
最新推荐文章于 2022-08-16 10:15:43 发布
本文详细介绍了一种自定义的TurnTableView控件实现方法。该控件能够在Android应用中响应触摸事件,通过手势监听器获取用户手指在屏幕上的滑动坐标,并判断手指是否位于指定图像上。文章提供了完整的代码示例,包括如何测量控件尺寸、绘制图像以及处理触摸事件。
841

被折叠的 条评论
为什么被折叠?



