java - 如何找到 ImageView 上触摸的所有像素?

标签 java android bitmap imageview pixel

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

最佳答案

好的,乔纳,这里有一些指导。
我猜你希望混合效果对用户输入快速使用react,所以首先你最好选择自定义 SurfaceView 而不是 ImageView,因为它更适合绘制 2D Action 游戏和动画所需的高帧率动画。我强烈建议您阅读this guide ;在继续之前,请特别注意有关使用 SurfaceView 的部分。您基本上需要创建一个扩展 SurfaceView 并实现 SurfaceHolder.Callback 的类。然后,该 View 将负责监听用户触摸事件并渲染帧以动画混合效果。
看一下下面的代码作为引用:

    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
        }
    }

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

    <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);
            }
        }

使用功能齐全的示例来给出答案是不切实际的,因此我建议您下载 Lunar Lander sample game from Google完整的工作示例。但请注意,如果您需要的只是混合效果,那么您将不需要游戏动画线程(尽管拥有一个游戏动画线程不会有什么坏处),就像 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
    }

}

这段代码对我有用。我只是希望我没有忘记任何事情 =:)
如果您仍然遇到问题,请告诉我,好吗?

关于java - 如何找到 ImageView 上触摸的所有像素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27628985/

相关文章:

Java JUNG EdmondsKarpMaxFlow 陷入无限循环

android - EditText 颜色光标和标记

android - 使用本地 js/css 加载网站

java - Android - 使用位图作为渐变 mask

java - Nutch 2.4 注入(inject)出现运行时异常

java - Twitter4j:java.lang.IllegalStateException:访问 token 已可用

java - 并行调用 OkHttpClient 是线程安全的吗?

android - 如何实现 PeriodicWorkRequest 链?

java - 用图库选择的图像比用相机拍摄的图像大得多

android - 为什么 fresco 在 android 5.0 或更高版本上选择不将位图放入 ashmem