web-dev-qa-db-ja.com

imageviewのようにビットマップセンターをトリミングする方法は?

可能性のある複製:
解析された画像をAndroidでトリミングする方法は?

Androids ImageViewと同じように作物を刈る方法

Android:scaleType="centerCrop"
26
ericlee

あなたの質問はあなたが達成したいことに関する情報が少し不足していますが、私はあなたがビットマップを持っていて、それを新しいサイズにスケーリングしたいと思い、ImageCenterに対して「centerCrop」が機能するようにスケーリングが行われるべきだと思います。

から Docs

画像の両方の寸法(幅と高さ)がビューの対応する寸法(マイナスのパディング)以上になるように、画像を均一にスケーリングします(画像のアスペクト比を維持)。

私の知る限り、これを行うためのワンライナーはありません(間違っている場合は修正してください)が、独自のメソッドを記述してそれを行うことができます。次のメソッドは、元のビットマップを新しいサイズにスケーリングし、結果のビットマップの中央に描画する方法を計算します。

それが役に立てば幸い!

public Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) {
    int sourceWidth = source.getWidth();
    int sourceHeight = source.getHeight();

    // Compute the scaling factors to fit the new height and width, respectively.
    // To cover the final image, the final scaling will be the bigger 
    // of these two.
    float xScale = (float) newWidth / sourceWidth;
    float yScale = (float) newHeight / sourceHeight;
    float scale = Math.max(xScale, yScale);

    // Now get the size of the source bitmap when scaled
    float scaledWidth = scale * sourceWidth;
    float scaledHeight = scale * sourceHeight;

    // Let's find out the upper left coordinates if the scaled bitmap
    // should be centered in the new size give by the parameters
    float left = (newWidth - scaledWidth) / 2;
    float top = (newHeight - scaledHeight) / 2;

    // The target rectangle for the new, scaled version of the source bitmap will now
    // be
    RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);

    // Finally, we create a new bitmap of the specified size and draw our new,
    // scaled bitmap onto it.
    Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
    Canvas canvas = new Canvas(dest);
    canvas.drawBitmap(source, null, targetRect, null);

    return dest;
}
90
Albin