Search code examples
androidcanvasbitmappreview

Touch point zoom preview


I am working on scan Document program where i have already developed a program which scan document with image processing and give option to crop image same like CanScanner.

Now I want touch image zoom preview just like cam scanner gives option. How will i achieve this feature. Please find attached image for reference (same feature i want to develope)

Please help to achieve this feature.

Thanks in advance Reference image for feature


Solution

  • You can create and use a BitmapShader (using the bitmap of the image you're drawing), a Matrix and a Paint.

    mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
    mShader = new BitmapShader(mBitmap, TileMode.CLAMP, TileMode.CLAMP);
    
    mPaint = new Paint();
    mPaint.setShader(mShader);
    

    Then setup a gesture motion event to record the touch position. We will set up the shader's matrix base on this position in the next step.

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        int action = event.getAction(); 
    
        zoomPos.x = event.getX();
        zoomPos.y = event.getY();
    
        switch (action) { 
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_MOVE:
            zooming = true;
            this.invalidate();
            break; 
        case MotionEvent.ACTION_UP:   
        case MotionEvent.ACTION_CANCEL:
            zooming = false;
            this.invalidate();
            break; 
    
        default: 
            break; 
        }
    
        return true; 
    }
    

    Then in the drawing code, use postScale() to scale and translate the matrix base on coordinate of the crop region. Then draw a circle to display the magnifier using the shader Paint.

    @Override
    protected void onDraw(Canvas canvas) {
    
        super.onDraw(canvas);
    
        if (zooming) {
            matrix.reset();
            matrix.postScale(2f, 2f, zoomPos.x, zoomPos.y);
            mPaint.getShader().setLocalMatrix(matrix);
    
            canvas.drawCircle(zoomPos.x, zoomPos.y, 100, mPaint);
        }
    }
    

    See: Android - How to circular zoom/magnify part of image? and Magnifying part of the canvas when touched