繁体   English   中英

如何找到图像视图上触摸的所有像素?

[英]How to find all pixels touched on an image view?

在我的应用程序上,我有一个ImageView,我将其转换为可编辑的位图。 我需要检测用户触摸了ImageView上的哪些像素。 此外,如果用户用手指画一条线,我需要知道所有被触摸过的像素才能进行更改。 如何检测触摸了哪些像素?

好的,乔纳,这是您的一些指示。
我想您想让混合效果对用户输入快速做出反应,所以第一件事最好是使用自定义SurfaceView而不是ImageView,因为它更适合绘制2D动作游戏和动画中所需的高帧频动画。 我强烈建议您阅读本指南 在继续之前,请特别注意有关SurfaceView的使用。 基本上,您将需要创建一个扩展SurfaceView并实现SurfaceHolder.Callback 然后,此视图将负责侦听用户的触摸事件并渲染帧以动画化混合效果。
请看以下代码作为参考:

    public class MainView extends SurfaceView implements SurfaceHolder.Callback {
        public MainView(Context context, AttributeSet attrs) {
            super(context, attrs);
            SurfaceHolder holder = getHolder(); 
            holder.addCallback(this);        // Register this view as a surface change listener
            setFocusable(true);              // make sure we get key events
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            super.onTouchEvent(event);

            // Check if the touch pointer is the one you want
            if (event.getPointerId(event.getActionIndex()) == 0) {
                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    // User touched screen...
                case MotionEvent.ACTION_CANCEL:
                    // User dragged his finger out of the view bounds...
                case MotionEvent.ACTION_UP:
                    // User raised his finger...
                case MotionEvent.ACTION_MOVE:
                    // User dragged his finger...

                // Update the blending effect bitmap here and trigger a frame redraw,
                // if you don't already have an animation thread to do it for you.

                return true;
            }

            return false;
        }

        /*
         * Callback invoked when the Surface has been created and is ready to be
         * used.
         */
        public void surfaceCreated(SurfaceHolder holder) {
            // You need to wait for this call back before attempting to draw
        }

        /*
         * Callback invoked when the Surface has been destroyed and must no longer
         * be touched. WARNING: after this method returns, the Surface/Canvas must
         * never be touched again!
         */
        public void surfaceDestroyed(SurfaceHolder holder) {
            // You shouldn't draw to this surface after this method has been called
        }
    }

然后在“绘图”活动的布局上使用它,如下所示:

    <com.xxx.yyy.MainView
        android:id="@+id/main_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

要绘制此表面,您需要以下代码:

        Canvas c = null;

        try {
            c = mSurfaceHolder.lockCanvas(null);

            synchronized (mSurfaceHolder) {
                if (c != null)
                    c.drawBitmap(blendingImage, 0, 0, null);   // Render blending effect
            }
        } catch (Exception e) {
            Log.e("SurfaceView", "Error drawing frame", e);
        } finally {
            // do this in a finally so that if an exception is thrown
            // during the above, we don't leave the Surface in an
            // inconsistent state
            if (c != null) {
                mSurfaceHolder.unlockCanvasAndPost(c);
            }
        }

不能提供完整功能的示例来回答问题,因此建议您从Google下载Lunar Lander示例游戏以获取完整的示例。 但是请注意,您不需要游戏动画线程(尽管拥有一个动画线程也不会受到伤害),就像Lunar Lander示例中编码的那样,如果您需要的只是混合效果。 该线程的目的是创建一个游戏循环,在该循环中不断生成游戏框架以对可能依赖或不依赖用户输入的对象进行动画处理。 在您的情况下,您需要做的就是在处理每个触摸事件后触发框架重绘。

编辑:下面的代码是修复程序,以获取您在注释中提供的代码,可以正常工作。
这是对MainActivity的更改:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // put pics from drawables to Bitmaps
    Resources res = getResources();
    BitmapDrawable bd1 = (BitmapDrawable) res.getDrawable(R.drawable.pic1);

    // FIX: This block makes `operation` a mutable bitmap version of the loaded resource
    // This is required because immutable bitmaps can't be changed
    Bitmap tmp = bd1.getBitmap();
    operation = Bitmap.createBitmap(tmp.getWidth(), tmp.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(operation);
    Paint paint = new Paint();
    c.drawBitmap(tmp, 0f, 0f, paint);

    BitmapDrawable bd2 = (BitmapDrawable) res.getDrawable(R.drawable.pic2);
    bmp = bd2.getBitmap();

    myView = new MainView(this, operation, bmp);
    FrameLayout preview = (FrameLayout) findViewById(R.id.preview);
    preview.addView(myView);

}
...

这是对MainView类的更改:

public class MainView extends SurfaceView implements Callback {

    private SurfaceHolder holder;
    private Bitmap operation;
    private Bitmap bmp2;
    private boolean surfaceReady;

    // took out AttributeSet attrs
    public MainView(Context context, Bitmap operation, Bitmap bmp2) {
        super(context);

        this.operation = operation;
        this.bmp2 = bmp2;

        holder = getHolder();     // Fix: proper reference the instance variable
        holder.addCallback(this); // Register this view as a surface change
                                    // listener
        setFocusable(true); // make sure we get key events
    }

    // Added so the blending operation is made in one place so it can be more easily upgraded
    private void blend(int x, int y) {
        if (x >= 0 && y >= 0 && x < bmp2.getWidth() && x < operation.getWidth() && y < bmp2.getHeight() && y < operation.getHeight())
            operation.setPixel(x, y, bmp2.getPixel(x, y));
    }

    // Added so the drawing is now made in one place
    private void drawOverlays() {
        Canvas c = null;
        try {
            c = holder.lockCanvas(null);
            synchronized (holder) {
                if (c != null)
                    c.drawBitmap(operation, 0, 0, null); // Render blending
                                                            // effect
            }
        } catch (Exception e) {
            Log.e("SurfaceView", "Error drawing frame", e);
        } finally {
            // do this in a finally so that if an exception is thrown
            // during the above, we don't leave the Surface in an
            // inconsistent state
            if (c != null) {
                holder.unlockCanvasAndPost(c);
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);

        if (!surfaceReady)     // No attempt to blend or draw while surface isn't ready
            return false;

        // Check if the touch pointer is the one you want
        if (event.getPointerId(event.getActionIndex()) == 0) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // User touched screen. Falls through ACTION_MOVE once there is no break

            case MotionEvent.ACTION_MOVE:
                // User dragged his finger...
                blend((int) event.getX(), (int) event.getY());

            }
            // Update the blending effect bitmap here and trigger a frame
            // redraw,
            // if you don't already have an animation thread to do it for you.
            drawOverlays();
            return true;
        }

        return false;
    }

    /*
     * Callback invoked when the Surface has been created and is ready to be
     * used.
     */
    public void surfaceCreated(SurfaceHolder holder) {
        surfaceReady = true;
        drawOverlays();
    }

    /*
     * Callback invoked when the Surface has been destroyed and must no longer
     * be touched. WARNING: after this method returns, the Surface/Canvas must
     * never be touched again!
     */
    public void surfaceDestroyed(SurfaceHolder holder) {
        // You shouldn't draw to this surface after this method has been called
        surfaceReady = false;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        // TODO Auto-generated method stub
    }

}

该代码对我有用。 我只是希望我不会忘记任何事情= :)
让我知道您是否仍然遇到麻烦,好吗?

因此,答案是您必须要聪明一点,但事实并非如此。 除了在此处发布所有代码以完成您想要的工作之外,我在这里为您提供链接和说明。

因此,通过管理应用程序的触摸事件,您可以算出触摸事件的平均坐标。 使用该信息,您可以确定触摸的所有像素的中心,并在用手指画一条线时继续跟踪。 要跟踪直线,请使用

case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:

子句确定行的开始和结束。 如果要跟踪不直线且未绘制的线,则需要使用

case MotionEvent.ACTION_MOVE:

那应该可以让您开始。 您可能需要一点逻辑来处理这样的事实,即您会画一条很细的线,我怀疑这并不是您想要的。 也许是这样。 无论哪种方式,这都应该是一个入门的好地方。

编辑

关于您的第一条评论, 是您可以使用的链接示例。 不过,我必须作一个小的声明。 为了使所有部分正确地协同工作,乍一看似乎并不那么简单。 我向您保证,这是最简单的示例之一,并将本教程分为几节。

对于您想做的事情,我想您需要特别注意第2节(不要与第2步混淆):

 2. Facilitate Drawing

我建议这样做,因为它显示了使用TouchEvent来使用信息的不同方法。 第1节中的内容将稍微解释一下设置显示TouchEvent捕获数据的环境,而第3节中的大部分内容是美学。 这可能无法直接回答您的问题,但是我怀疑它将带您到达需要的地方。

编码愉快! 如有任何疑问,请发表评论。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM