0

我是位图新手。我知道如何在 android 中调整或缩放位图。但问题是假设我的图像是 100x500 或任何高度和宽度。现在我想调整它的大小,如 100x100。怎么可能

请帮助我。

4

3 回答 3

7

对于这种简单的情况,最合理的做法是将源图像向下平移到中间,然后在新的 Canvas 上再次绘制位图。这种类型的调整大小在 Android中称为中心裁剪。中心裁剪的想法是产生填充整个边界的最大图像,并且不改变纵横比。

您可以自己实现这一点,以及其他类型的调整大小和缩放。基本上,您使用矩阵来发布您的更改,例如缩放和移动(平移),然后在考虑矩阵的画布上绘制您的原始位图。

这是我从另一个答案here中采用的一种方法(找不到原始帖子以正确给予信用):

public static Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth)
{
    int sourceWidth = source.getWidth();
    int sourceHeight = source.getHeight();
    float xScale = (float) newWidth / sourceWidth;
    float yScale = (float) newHeight / sourceHeight;
    float scale = Math.max(xScale, yScale);

    //get the resulting size after scaling
    float scaledWidth = scale * sourceWidth;
    float scaledHeight = scale * sourceHeight;

    //figure out where we should translate to
    float dx = (newWidth - scaledWidth) / 2;
    float dy = (newHeight - scaledHeight) / 2;

    Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
    Canvas canvas = new Canvas(dest);
    Matrix matrix = new Matrix();
    matrix.postScale(scale, scale);
    matrix.postTranslate(dx, dy);
    canvas.drawBitmap(source, matrix, null);
    return dest;
}
于 2012-12-11T16:20:47.813 回答
1
int dstWidth = 100;
int dstHeight = 100;
boolean doFilter = true;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(src, dstWidth, dstHeight, doFilter);
于 2012-12-11T16:26:13.740 回答
0

对 wsanville 的代码进行了一些修改..它对我有用 请注意,我使用的是最小比例(取最小比例,以便整个位图可以在屏幕上呈现..如果我取最大值,那么它可能会超出屏幕

        int sourceWidth = mBitmap.getWidth();
        int sourceHeight = mBitmap.getHeight();
        float xScale = (float) newWidth / sourceWidth;
        float yScale = (float) newHeight / sourceHeight;

        float scale = Math.min(xScale, yScale);

        //get the resulting size after scaling
        float scaledWidth = scale * sourceWidth;
        float scaledHeight = scale * sourceHeight;

        //figure out where we should translate to
        float dx = (newWidth - scaledWidth) / 2;
        float dy = (newHeight - scaledHeight) / 2;

        Matrix defToScreenMatrix = new Matrix();


        defToScreenMatrix.postScale(scale, scale);
        defToScreenMatrix.postTranslate(dx, dy);

        mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, sourceWidth, sourceHeight, defToScreenMatrix, false);
于 2013-10-27T03:32:20.557 回答