简体   繁体   中英

Center align bitmap in canvas android

I am adding black to image bitmap using this but my bitmap is always on top need to center align it.

Here is code i am using

Bitmap resizeBitmap(Bitmap image, int destWidth, int destHeight) {
    Bitmap background = Bitmap.createBitmap(destWidth, destHeight, Bitmap.Config.ARGB_8888);
    float originalWidth = image.getWidth();
    float originalHeight = image.getHeight();
    Canvas canvas = new Canvas(background);

    float scaleX = (float) 1280 / originalWidth;
    float scaleY = (float) 720 / originalHeight;

    float xTranslation = 0.0f;
    float yTranslation = 0.0f;
    float scale = 1;

    if (scaleX < scaleY) { // Scale on X, translate on Y
        scale = scaleX;
        yTranslation = (destHeight - originalHeight * scale) / 2.0f;
    } else { // Scale on Y, translate on X
        scale = scaleY;
        xTranslation = (destWidth - originalWidth * scale) / 2.0f;
    }

    Matrix transformation = new Matrix();
    transformation.postTranslate(xTranslation, yTranslation);
    transformation.preScale(scale, scale);
    Paint paint = new Paint();
    paint.setFilterBitmap(true);
    canvas.drawBitmap(image, transformation, paint);
    return background;
}

Any solution android

float boardPosX = ((canvasx/2) - (bitmapx / 2));
float boardPosY = ((canvasy/2) - (bitmapy / 2));

and more like this

Try This

 public Bitmap resizeBitmap(Bitmap image, int destWidth, int destHeight) {
        if (image == null) {
            return null;
        }

        int width = image.getWidth();
        int height = image.getHeight();

        if (width < destWidth && height < destHeight) {
            return image;
        }
        int x = 0;
        int y = 0;
        if (width > destWidth) {
            x = (width - destWidth) / 2;
        }
        if (height > destHeight) {
            y = (height - destHeight) / 2;
        }
        int cw = destWidth;
        int ch = destHeight;
        if (destWidth > width) {
            cw = width;
        }
        if (destHeight > height) {
            ch = height;
        }

        Bitmap output = Bitmap.createBitmap(image, x, y, cw, ch);
        Bitmap background = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(background);

        Paint paint = new Paint();
        paint.setFilterBitmap(true);
        canvas.drawColor(Color.BLACK);
        canvas.drawBitmap(output, x, y, paint);

        return background;
    }

output like this

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM