简体   繁体   English

在画布android中居中对齐位图

[英]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像这样输出

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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