androidbitmapandroid-canvassurfaceviewdirtyrectangle

Bitmap is not exactly fit into rectangle in android


I am developing an RDP client application using android-V11.

Server: The screen is divided into 4 parts and sending the image data in byte[], left,top, right, bottom, Screen resolution(width --> 1024/1280, height --? 768/ 1024) values for each frame to client.

Client: I am using surface view to display the images receiving from server. I need to display the 4frames(one screen of server) to fit exactly into the tablet screen.

The Sample code:

 class mySurfaceView extends SurfaceView implements SurfaceHolder.Callback
    {



       class TutorialThread extends Thread 
       {
         @Override
         public void run() 
         {
           Canvas c = null;
          // Socket commnuication
           ......
         Bitmap bmp;
          while(true){
           c=null;
           //logic to get the details from server
          .....
         bmp = BitmapFactory.decodeByteArray(imageBytes, 0,imageBytes.length);

        //Logic to calculate the Top Left, right bottom corners to divide the tablet screen into   4parts for 4 frames receiving from server
          .....

    //Frame rectangle for each frame

        Rect rect = new Rect(newLeft, newTop,newWidth,newHeight);

    //display image

       try{

        c  = _surfaceHolder.lockCanvas(rect);

        if(c!=null){
            synchronized (_surfaceHolder) 
            {
                       c.drawBitmap(scaledBitmap, newLeft,newTop, paint);
                    }
              }
          }
          finally{
        if(c!=null){                                     _surfaceHolder.unlockCanvasAndPost(c);
               }
        }
        //End of while
    }
    //End of run()
    }
    //End Tutorial Thread
    }
    //End of surfaceView
    }

We are unable to fit the bitmap exactly into the rectangle. The frames are displayed in tablet with gaps between them.

After debugging code it seems like the retrieved bitmap(bmp) width is 514, and the rectangle (rect) width is 640. So, the bitmap doesn't fit into the rectangle.

Could please tell me how to scale the bitmap to fit exactly into rectangle.

Note: I also need Pinch Zoom the image.

Thanks & Regards Yamini.


Solution

  • First get the height and width of the bitmap,

    final int height= bitmap.getHeight() ;
    final int width= bitmap.getWidth();
    float h= (float) height;
    float w= (float) width;
    

    Now lets the position of your rectangle is ( newLeft, newTop ) and height, width is newHeight and newWidth respectively

    Now set the position and scaling factor to a matrix object

    Matrix mat=new Matrix();
    mat.setTranslate( newLeft, newTop );
    mat.setScale(newWidth/w ,newHeight/h);
    

    now draw your bitmap with the matrix

    canvas.drawBitmap(bitmap, mat, new paint());
    

    Now your bitmap will fill the rectangle..

    try it, all the best.!