Android - Draw Bitmap within Canvas

后端 未结 2 1536
醉酒成梦
醉酒成梦 2020-12-09 13:49

I currently have a maze game which draws a 5 x 5 square (takes the width of screen and splits it evenly). Then for each of these boxes using x and y cordinates I user drawRe

相关标签:
2条回答
  • 2020-12-09 14:03

    Use the Canvas method public void drawBitmap (Bitmap bitmap, Rect src, RectF dst, Paint paint). Set dst to the size of the rectangle you want the entire image to be scaled into.

    EDIT:

    Here's a possible implementation for drawing the bitmaps in squares across on the canvas. Assumes the bitmaps are in a 2-dimensional array (e.g., Bitmap bitmapArray[][];) and that the canvas is square so the square bitmap aspect ratio is not distorted.

    private static final int NUMBER_OF_VERTICAL_SQUARES = 5;
    private static final int NUMBER_OF_HORIZONTAL_SQUARES = 5;
    

    ...

        int canvasWidth = canvas.getWidth();
        int canvasHeight = canvas.getHeight();
    
        int squareWidth = canvasWidth / NUMBER_OF_HORIZONTAL_SQUARES;
        int squareHeight = canvasHeight / NUMBER_OF_VERTICAL_SQUARES;
        Rect destinationRect = new Rect();
    
        int xOffset;
        int yOffset;
    
        // Set the destination rectangle size
        destinationRect.set(0, 0, squareWidth, squareHeight);
    
        for (int horizontalPosition = 0; horizontalPosition < NUMBER_OF_HORIZONTAL_SQUARES; horizontalPosition++){
    
            xOffset = horizontalPosition * squareWidth;
    
            for (int verticalPosition = 0; verticalPosition < NUMBER_OF_VERTICAL_SQUARES; verticalPosition++){
    
                yOffset = verticalPosition * squareHeight;
    
                // Set the destination rectangle offset for the canvas origin
                destinationRect.offsetTo(xOffset, yOffset);
    
                // Draw the bitmap into the destination rectangle on the canvas
                canvas.drawBitmap(bitmapArray[horizontalPosition][verticalPosition], null, destinationRect, null);
            }
        }
    
    0 讨论(0)
  • 2020-12-09 14:12

    Try the following code :

    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setFilterBitmap(true);
    paint.setDither(true);
    
    canvas.drawBitmap(bitmap, x, y, paint);
    

    ==================

    You could also just reference this answer.

    0 讨论(0)
提交回复
热议问题