如何在Android SurfaceView中屏蔽位图?

时间:2016-04-06 12:13:51

标签: android android-canvas surfaceview mask android-bitmap

我想要实现的目标:

这是我第一次使用SurfaceView,多线程和触摸事件。我正在尝试使用圆形位图蒙版来屏蔽矩形位图图像。我一直在尝试在SurfaceView中的一个线程中执行此操作。此SurfaceView还有一个onTouch()方法,当我拖动图像时,它将相对于将保持静止的蒙版移动。

问题:

掩码使用以下代码,但仅在while循环的第一次迭代中使用。当它第二次碰到unlockCanvasAndPost(画布)时,它会将掩码覆盖为底层位图顶部的图像,并且屏蔽停止生效。修复了ontouch事件中重绘的问题 - 见下文。

@Override
public void run() {

    while(isRunnable){
        // draw to the canvas

        //if the surface isn't available go back to the top of the loop
        if(!surfaceHolder.getSurface().isValid()){
            continue;
        }
        result = Bitmap.createBitmap(maskImage.getWidth(), maskImage.getHeight(), Bitmap.Config.ARGB_8888);

        //lock the canvas before trying to draw to it
        canvas = surfaceHolder.lockCanvas();
        maskPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        maskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));


        Canvas tempCanvas = new Canvas(result);
        //draw the bitmaps to the canvas
        canvas.drawARGB(255, 255, 255, 255);
        tempCanvas.drawBitmap(userIconImage, imageX, imageY, null);
        tempCanvas.drawBitmap(maskImage, maskX, maskY, maskPaint);
        maskPaint.setXfermode(null);
        canvas.drawBitmap(result,0,0,new Paint());
        surfaceHolder.unlockCanvasAndPost(canvas);

        result = null;

    }

}// run()

我尝试了什么:

This基本上有效。但是当我拖动以重新定位onTouch()中的imgage时,我得到了先前绘制的图像的痕迹。根据android.developer.com,你可以通过使用drawBitmap()Canvas and Drawables - SurfaceView section来避免这种情况。这就是我想要做的,但显然是错误的。我也不喜欢我必须在while循环中不断创建对象,并且如果可能的话我希望避免它。

我的onTouch()方法目前是这样的:

@Override
public boolean onTouch(View v, MotionEvent motionEvent) {

   try{
       Thread.sleep(50);
   }catch (InterruptedException e){
        e.printStackTrace();
   }

    switch (motionEvent.getAction()){

        case MotionEvent.ACTION_MOVE:
            imageX = motionEvent.getX();
            imageY = motionEvent.getY();
            break;
    }

    return true;
}

0 个答案:

没有答案