如何按照特殊规则以编程方式缩放和裁剪图像

问题描述

我想在显示之前以特定方式缩放和裁剪图像 - 取决于其初始尺寸及其宽度和高度比例。最后,我希望图像填满整个可用屏幕。

以下是我在缩放和裁剪时需要遵循的规则:

  1. 如果图像的宽度大于其高度: a) 放大或缩小图像的高度以匹配屏幕的高度,但保持图像的初始宽高比。 b) 将图像置于屏幕中央。 c) 对称裁剪两边多余的宽度空间以匹配屏幕的宽度。

  2. 如果图像的宽度小于其高度: a) 放大或缩小图像的宽度以匹配屏幕的宽度,但保持图像的初始宽度/高度比。 b) 将图像置于屏幕中央。 c) 对称裁剪两边多余的高度空间以匹配屏幕的高度。

我的目的是通过拉伸或缩小尺寸来填充整个屏幕,当与屏幕尺寸匹配时,会导致另一个图像尺寸超过屏幕尺寸,然后应居中并对称裁剪。

我当前的代码使任何图像填满屏幕,但它没有保持原始的宽/高比,这会导致失真。 下面我给出相关代码

Bitmap bmImg;
String[] PathsArray;
int numb_paths=0;
int position = 0;
ImageView imageView;
ViewFlipper flipper;
PathsArray = imagesPaths.split("\n");
numb_paths = PathsArray.length;
bmImg = BitmapFactory.decodeFile(PathsArray[position]);
imageView = new ImageView(displayImagesShow.this);
flipper = findViewById(R.id.flipper);
Resources r = getResources();
layers[0] = new BitmapDrawable(getResources(),bmImg);
layers[1] = r.getDrawable(R.drawable.flowers_frame1);
Drawable[] layers = new Drawable[2];
LayerDrawable layerDrawable = new LayerDrawable(layers);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setimageDrawable(layerDrawable);
ViewFlipper.LayoutParams lp =
        new ViewFlipper.LayoutParams
                (ViewFlipper.LayoutParams.MATCH_PARENT,ViewFlipper.LayoutParams.MATCH_PARENT);
imageView.setLayoutParams(lp);
flipper.addView(imageView);

解决方法

我自己找到了解决方案。它位于下面“/”的长行之间:

Bitmap bmImg,CroppedBmp;
String[] PathsArray;
int numb_paths=0;
int position = 0;
int wi,hi,wc,half_crop_dif,;
double ratioB
ImageView imageView;
ViewFlipper flipper;
PathsArray = imagesPaths.split("\n");
numb_paths = PathsArray.length;
bmImg = BitmapFactory.decodeFile(PathsArray[position]);
///////////////////////////////////////////////////////////////
wi = bmImg.getWidth();
hi = bmImg.getHeight();
ratioB = (double)wi/hi;
if(ratioB>ratio)
{
    wc = (int)(hi*ratio);
    half_crop_dif = (int)((wi-wc)/2.0);
    hi = (int)(hi*CORRECTION_FACTOR);
    CroppedBmp = Bitmap.createBitmap
            (bmImg,hi);
    
}
else
{
    hc = (int) (wi / ratio);
    half_crop_dif = (int) ((hi - hc )/ 2.0);
    CroppedBmp = Bitmap.createBitmap
    (bmImg,wi,hc);
}
bmImg = CroppedBmp;

///////////////////////////////////////////////////////////////
imageView = new ImageView(displayImagesShow.this);
flipper = findViewById(R.id.flipper);
Resources r = getResources();
layers[0] = new BitmapDrawable(getResources(),bmImg);
layers[1] = r.getDrawable(R.drawable.flowers_frame1);
Drawable[] layers = new Drawable[2];
LayerDrawable layerDrawable = new LayerDrawable(layers);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageDrawable(layerDrawable);
ViewFlipper.LayoutParams lp =
        new ViewFlipper.LayoutParams
                (ViewFlipper.LayoutParams.MATCH_PARENT,ViewFlipper.LayoutParams.MATCH_PARENT);
imageView.setLayoutParams(lp);
flipper.addView(imageView);