在画布中居中对齐位图Android

g6baxovj  于 2022-12-25  发布在  Android
关注(0)|答案(1)|浏览(144)

我添加黑色图像位图使用这个,但我的位图总是在顶部需要中心对齐它。
下面是我正在使用的代码

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;
}

任何解决方案android

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

更像这样

egmofgnx

egmofgnx1#

试试这个

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;
    }

输出如下

相关问题