使用 MotionEvent 在视图上同时移动两个位图

2024-04-06

我使用以下类(android 中的简单 2D 图形)在视图上创建了两个位图,并徘徊以实现位图可以独立移动。我为此调用motionevent 方法。

当前问题,我不明白为什么在下面的代码中只有一个对象向右移动。例如使用此代码,仅移动“不”位图,我想彼此独立地移动两个位图。

场景:我可以用两根手指(每个对象一根手指)独立移动位图。但我不知道如何实现这一目标。

public class TouchView extends View {

private Drawable cross;
private Rect crossBounds = null;
private Drawable not;
private Rect notBounds = null;

private int x1, y1, x2, y2 ;

boolean flag = true;

private void intialize ()
{ 
    int w1 = cross.getIntrinsicWidth();
    int h1 = cross.getIntrinsicHeight();
     x1 = 100;
    y1 = 100;
    crossBounds = new Rect(x1-w1/2, y1-w1/2, x1+w1/2, y1+h1/2);

    int w = not.getIntrinsicWidth();
    int h = not.getIntrinsicHeight();
     x2 = 300;
    y2 = 300;
    notBounds = new Rect(x2-w/2, y2-w/2, x2+w/2, y2+h/2);

}

public TouchView(Context context) {
    super(context);

    // Get a representation of the image
    Resources resources = context.getResources();
    cross = (Drawable) resources.getDrawable(R.drawable.cross);
    not = (Drawable) resources.getDrawable(R.drawable.not);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    Log.i("TouchView.onTouchEvent", "event = " + event);

    if(event.getAction() == MotionEvent.ACTION_DOWN || 
            event.getAction() == MotionEvent.ACTION_MOVE) {

        int touchCounter = event.getPointerCount();


         if (touchCounter ==2 && getHeight ()==y1){
                int w = cross.getIntrinsicWidth();
                int h = cross.getIntrinsicHeight();
                 x1 = (int) event.getX();

                crossBounds = new Rect(x1-w/2, y1-w/2, x1+w/2, y1+h/2);
                }
                else
                {
                int w1 = not.getIntrinsicWidth();
                int h1 = not.getIntrinsicHeight();
                 x2 = (int) event.getX();

                notBounds = new Rect(x2-w1/2, y2-w1/2, x2+w1/2, y2+h1/2);
                }
                // Request the system to redraw the view (call onDraw at 
                // some point in the future)
                // From a non-UI thread, call postInvalidate instead





        invalidate();

        return true;
    }

    return false;
}



@Override
protected void onDraw(Canvas canvas) {

    Log.i("TouchView.onDraw", "");

    // Background
    Paint bgPaint = new Paint();
    bgPaint.setColor(Color.WHITE);
    canvas.drawPaint(bgPaint);

    if (flag == true){
        intialize ();
        cross.setBounds(crossBounds);
        cross.draw(canvas);
        not.setBounds(notBounds);
        not.draw(canvas);
        flag=false;
    }
    if(crossBounds != null) {
        cross.setBounds(crossBounds);
        cross.draw(canvas);
        not.setBounds(notBounds);
        not.draw(canvas);
    }
}
}

public class SimpleDrag extends View {



private final int INVALID_INDEX = -1;

private final int mTotalItems = 5;

private ArrayList<Rect> mItemsCollection;

private ArrayList<Point> mActiveDragPoints;

private ArrayList<Rect>  mActiveRects;


private Paint mPaint;

/**
 * @param context  
 * @return of type SimpleDrag
 * Constructor function
 * @since Feb 19, 2013 
 * @author rajeshcp
 */
public SimpleDrag(Context context) {
    super(context);
    init();
}

/**
 * @param context
 * @param attrs  
 * @return of type SimpleDrag
 * Constructor function
 * @since Feb 19, 2013 
 * @author rajeshcp
 */
public SimpleDrag(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

/**
 * @param context
 * @param attrs
 * @param defStyle  
 * @return of type SimpleDrag
 * Constructor function
 * @since Feb 19, 2013 
 * @author rajeshcp
 */
public SimpleDrag(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
}

/* (non-Javadoc)
 * @see android.view.View#onDraw(android.graphics.Canvas)
 * @since Feb 19, 2013
 * @author rajeshcp 
 */
@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawColor(Color.BLUE, PorterDuff.Mode.CLEAR);
    for( Rect rect : mItemsCollection)
    {
        canvas.drawRect(rect, mPaint);
    }
}


/**
 * @param of type null
 * @return of type null
 * function which will initialize the view
 * @since Feb 20, 2013
 * @author rajeshcp
 */
private void init()
{
    mActiveRects      = new ArrayList<Rect>(mTotalItems);
    mActiveDragPoints = new ArrayList<Point>(mTotalItems);
    mItemsCollection  = new ArrayList<Rect>();
    for( int i = 0; i < mTotalItems; i++)
    {
        Rect rect = new Rect(i * 100, i * 100, (i + 1) * 100, (i + 1) * 100);
        mItemsCollection.add(rect);
    }
    mPaint     = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG | Paint.ANTI_ALIAS_FLAG);
    mPaint.setColor(Color.RED);
}





/* (non-Javadoc)
 * @see android.view.View#onTouchEvent(android.view.MotionEvent)
 * @since Feb 19, 2013
 * @author rajeshcp 
 */
@Override
public boolean onTouchEvent(MotionEvent event) {

    final int action  = event.getActionMasked();
    final int pointer = event.getActionIndex();

    switch (action) {
    case MotionEvent.ACTION_DOWN :
        Point touchDown = new Point((int)event.getX(), (int)event.getY());
        lookForIntersection(touchDown);
        break;
    case MotionEvent.ACTION_UP :
    case MotionEvent.ACTION_CANCEL :
        mActiveDragPoints.removeAll(mActiveDragPoints);
        mActiveRects.removeAll(mActiveRects);
        break;
    case MotionEvent.ACTION_MOVE :
        int count = 0;
        for(Rect rect : mActiveRects)
        {
            Point curretPoint = new Point((int)event.getX(count), (int)event.getY(count));
            moveRect(curretPoint, mActiveDragPoints.get(count), rect);
            count++;
        }
        Log.d(getClass().getName(), "Active Rects" + mActiveRects.size());
        Log.d(getClass().getName(), "Active Points" + mActiveDragPoints.size());
        invalidate();
        break;
    case MotionEvent.ACTION_POINTER_DOWN :
        touchDown = new Point((int)event.getX(pointer), (int)event.getY(pointer));
        lookForIntersection(touchDown);
        //Log.d(getClass().getName(), "ACTION_POINTER_DOWN" + pointer);
        break;
    case MotionEvent.ACTION_POINTER_UP :
        int index = getIntersectionRectIndex(new Point((int)event.getX(pointer), (int)event.getY(pointer)));
        if( index != INVALID_INDEX )
        {
            Rect rect = mItemsCollection.get(index);
            mActiveDragPoints.remove(mActiveRects.indexOf(rect));
            mActiveRects.remove(rect);
        }

        break;

    default:
        break;
    }
    return true;
}


/**
 * @param touchDown of type Point
 * @return of type null
 * function which will find the 
 * intersecting rect and add to the 
 * active collection
 * @since Feb 20, 2013
 * @author rajeshcp
 */
private void lookForIntersection(Point touchDown)
{
    final int index = getIntersectionRectIndex(touchDown);

    if( index != INVALID_INDEX )
    {
        final Rect rect = mItemsCollection.get(index);
        if( mActiveRects.indexOf(rect) == INVALID_INDEX )
        {
            mActiveDragPoints.add(touchDown);
            mActiveRects.add(mItemsCollection.get(index));
        }
    }
    Log.d(getClass().getName(), "Active Rects" + mActiveRects.size());
    Log.d(getClass().getName(), "Active Points" + mActiveDragPoints.size());

}




/**
 * @param point of type Point
 * @return of type int 
 * function which will return the index of 
 * the rect contaning the given point
 * @since Feb 20, 2013
 * @author rajeshcp
 */
private int getIntersectionRectIndex(final Point point)
{
    int index = INVALID_INDEX;
    for(Rect rect : mItemsCollection)
    {
        if( rect.contains(point.x, point.y) )
        {
            index = mItemsCollection.indexOf(rect);
            break;
        }
    }
    return index;
}


/**
 * @param currentPoint of type Point
 * @param prevPoint of type Point 
 * @param rect of type Rect
 * @return of type null
 * function which will move the change the 
 * bounds of teh rect
 * @since Feb 20, 2013
 * @author rajeshcp
 */
private void moveRect(Point currentPoint, Point prevPoint, final Rect rect)
{
    int xMoved = currentPoint.x - prevPoint.x;
    int yMoved = currentPoint.y - prevPoint.y;
    rect.set(rect.left + xMoved, rect.top + yMoved, rect.right + xMoved, rect.bottom + yMoved);
    mActiveDragPoints.set(mActiveDragPoints.indexOf(prevPoint), currentPoint);
}

}

希望这是您想要的,还没有进行很多测试,但基本上这对我有用,即使您可以通过更改 mTotalItems 来增加 nof 项目。希望这会有所帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 MotionEvent 在视图上同时移动两个位图 的相关文章

  • 在 Android 模拟器中获取互联网连接

    我有一台带有wifi连接的台式电脑 我的IP地址是192 168 12 95 网关是192 168 10 10 但是我在android模拟器中没有获得互联网连接 也就是说我无法访问internate 我也尝试过 emulator avd w
  • 我可以使用 Selenium Webdriver 测试元素的顺序吗?

    有一个表单 其中有 3 个字段 具有 3 个不同的 ID fieldset div div fieldset
  • 如何在java中从包含.0的浮点数中删除小数部分

    我只想删除包含的浮点数的小数部分 0 所有其他数字都是可以接受的 例如 I P 1 0 2 2 88 0 3 56666 4 1 45 00 99 560 O P 1 2 2 88 3 567 4 1 45 99 560 有什么方法可以做到
  • 如何创建用于测试的对象的 PagedList?

    我一直在使用 Google 的 arch 库 但是让测试变得困难的一件事是使用PagedList 对于此示例 我使用存储库模式并从 API 或网络返回详细信息 因此 在 ViewModel 中 我调用此接口方法 override fun g
  • Java 声音可视化器

    我正在尝试制作一个java声音可视化工具 但我完全不知道如何在实时处理音频后立即从提取的音频中获取字节 我可以将程序与 wav 文件同步 但这不是我想要做的 我想用程序生成声音 然后播放它 而不将其保存在任何地方 谢谢您的帮助 本文可以帮助
  • 不使用 length() 方法的字符串长度[关闭]

    Closed 这个问题需要细节或清晰度 help closed questions 目前不接受答案 如何在不使用字符串的情况下找到字符串的长度length String类的方法 str toCharArray length应该管用 或者怎么
  • java中永远不会出现的异常

    我为点和向量编写一个类 我想用它们来计算向量的点和范数 这些是点类和向量类 public class Point public float x y public class MyVector public Point start end 我
  • 使用 Haskell 将函数注入到 Java .class 文件中

    我使用 Haskell 编写了一个 Java 字节码解析器 它工作得很好 然而下一步让我完全难住了 我的 Haskell 程序需要修改 class 文件 以便在执行时 Java 程序打印 输入 此处的方法名称 在执行方法之前 并且 退出 此
  • 安卓浮动键盘

    是否可以通过编程方式更改键盘的位置 我正在开发一个图腾应用程序 如果键盘停靠在底部 则很难使用 我尝试创建一个扩展 InputMethodService 的自定义键盘 并且我能够更改按键的布局 但我无法更改键盘的视图位置 快捷键 https
  • androidx.navigation.fragment.NavHostFragment 无法从 xml 文件访问

    我正在尝试使用带有底部导航视图的 androidx 导航 因此 当我在 xml 文件中放置带有 android name androidx navigation fragment NavHostFragment 的片段时 它会给我一个错误
  • 为什么replaceAll在这行代码中不起作用? [复制]

    这个问题在这里已经有答案了 String weatherLocation weatherLoc 1 toString weatherLocation replaceAll how weatherLocation replaceAll wea
  • 短 2 个字节

    我正在从串行端口读取一个长度为 133 字节的数据包 最后 2 个字节包含 CRC 值 我使用 Java 将 2 个字节值制成单个 我认为很短 这就是我所做的 short high 48 0x00ff short low 80 short
  • 在Java内存管理中,“PS”代表什么?

    每当我看到 Java 中对内存的引用时 各种空格总是以 PS 为前缀 PS 是什么意思 它开始困扰我 到目前为止我唯一的猜测是 泳池空间 但这将是多余的 例子 PS伊甸园空间 PS 幸存者空间 PS 终身空间 老一代 PS Perm Gen
  • 对于双核手机,availableProcessors() 返回 1

    我最近购买了一部 Moto Atrix 2 手机 当我尝试查看手机中的处理器规格时 Runtime getRuntime availableProcessors 返回 1 proc cpuinfo 也仅包含有关处理器 0 的信息 出于好奇
  • 如何在 Hibernate 中自动递增复合主键中的 Id?

    我有一个带有复合主键的表 groupId and batchId 实体类看起来像 Entity name EMPLOYEE public class Employee EmbeddedId private EmployeePK employ
  • android 填充包含片段的布局

    问题是什么 我如何膨胀包含片段的布局 我不知道错误消息的含义 请帮我 谢谢 错误信息 09 01 18 44 58 698 E AndroidRuntime 20617 Caused by java lang IllegalArgument
  • 在 servlet 会话和 java.io.NotSerializedException 中保存对象

    SEVERE IOException while loading persisted sessions java io WriteAbortedException writing aborted java io NotSerializabl
  • 将其元素添加到另一个列表后清除列表

    我正在做一个程序 它获取更多句子作为参数 我制作了 2 个列表 一个称为 propozitie 其中包含每个句子 另一个称为 propozitii 其中包含所有句子 问题是 当我在遇到 后清除 propozitie 列表时 它也会清除 pr
  • Android:防止嗅探(例如使用 CharlesProxy)SSL 流量

    我使用 Charles 检查将我的应用程序发送到 HTTPS 的数据 我在手机上安装了 Charles CA 证书 因此我能够解密每个 SSL 流量 但我发现一些应用程序无法看到 SSL 流量 我如何将这种行为实现到我自己的应用程序中 有了
  • 允许使用 SurfaceTexture 在 GLSurfaceView 渲染器中进行多通道渲染

    我正在显示视频GLSurfaceView使用需要连续应用多个着色器的自定义渲染器 目前 它可以成功地使用一个着色器 但我不确定如何扩展渲染管道以连续应用多个着色器 我知道有一些关于应用多个着色器的示例 使用FrameBuffers and

随机推荐