0

私はビットマップを初めて使用します。Androidでビットマップのサイズを変更または拡大縮小する方法を知っていますが、問題は、画像が100x500または任意の高さと幅であると想定しています。100x100のような正方形にサイズ変更したいのですが、どうすればよいですか。

親切に私を助けてください。

4

3 に答える 3

7

この単純なケースの場合、最も合理的な方法は、ソースイメージを中央まで変換し、新しいキャンバスにビットマップを再度描画することです。このタイプのサイズ変更は、Androidではセンタークロップと呼ばれます。センタークロップのアイデアは、境界全体を塗りつぶし、アスペクト比を変更しない最大の画像を生成することです。

これは、他のタイプのサイズ変更やスケーリングとともに、自分で実装できます。基本的に、マトリックスを使用して、スケーリングや移動(変換)などの変更を投稿し、マトリックスを考慮したキャンバスに元のビットマップを描画します。

これが私がここで別の答えから採用した方法です(適切にクレジットを与えるための元の投稿が見つかりません):

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 に答える