Search code examples
androidandroid-canvasandroid-bitmap

DrawBitmap with Matrix not Accurate


I'm trying to use Canvas.drawBitmap(...) to draw Bitmaps onto a Canvas but it's not appearing in the correct position or size.

Below is an example on how I'm attempting to achieve this:

Canvas canvas = new Canvas();
Matrix matrix = new Matrix();

/// scale = 0.5
/// image.getX() = 250
/// image.getY() = 250
matrix.setTranslate(
        imageView.getX() * scale,
        imageView.getY() * scale
);

matrix.setScale(
        scale,
        scale
);

matrix.postRotate(imageView.getRotation(), imageView.getX() * scale, imageView.getY() * scale);

canvas.drawBitmap(bitmap, matrix, null);

The result that I'm getting is that the image is at the original size at 0x0 position.
The expected result is for the image to be half-size and in the center of the canvas.

NOTE: I'm using matrix.postRotate(...) to draw the bitmap rotated to the same angle as the ImageView.


Solution

  • Can you give this a shot, I have tried to explain the logic in the comments:

    // as you wanted Half size so reduced width and height to half
    
      Bitmap dstBitmap = Bitmap.createScaledBitmap(srcbitmap,(srcbitmap.getWidth()/2 ),(srcbitmap.getHeight()/2),true);
    
                    // Here I calculate screen size
                    DisplayMetrics displayMetrics = new DisplayMetrics();
                    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
                    int height = displayMetrics.heightPixels;
                    int width = displayMetrics.widthPixels;
    
       //Create screen size bitmap to position image at center easily
                    Bitmap bitmap = Bitmap.createBitmap(
                            width, 
                            height, 
                            Bitmap.Config.ARGB_8888 
                    );
    
                    // Initialize a new Canvas  with above bitmap
                    Canvas canvas = new Canvas(bitmap);
    
    
                 
               Matrix matrix = new Matrix();
    
    
                // Rotating about center of image
                matrix.setRotate(
                        45, // your angle
                        dstBitmap.getWidth() / 2, 
                        dstBitmap.getHeight() / 2 
                );
    
      
                matrix.postTranslate(
                        (width  - dstBitmap.getWidth()) / 2,
                        (height - dstBitmap.getHeight() )/ 2
                );
    
               
    
                canvas.drawBitmap(dstBitmap, matrix, null);
    

    Now you should be good to proceed , this should give you correct output