XML 中的缩放和裁剪图像

pax*_*axx 5 android android-layout android-imageview

我试图同时缩放和裁剪图像并从左到右屏幕边缘显示它。我收到的图像只比用户屏幕宽一点,我可以像这样缩放它(XML):

<ImageView
        android:id="@+id/category_image_top"
        android:layout_width="match_parent"
        android:layout_height="170dp"
        android:maxHeight="170dp"
        android:scaleType="centerCrop"
        android:adjustViewBounds="true" 
        android:focusable="false"
        />
Run Code Online (Sandbox Code Playgroud)

但这就是我得到的: 我得到什么

我想将图像对齐到右上角,如下所示: 我想要的是

这可能吗?我已经尝试了所有的scaleTypes,但注意到有效,图像要么缩放以适合X和Y(fitXY,fitStart),要么裁剪图像但居中(centerCrop)。我需要类似 android:scaleType="cropStart"

小智 5

<ImageView
        android:id="@+id/category_image_top"
        android:layout_width="match_parent"
        android:layout_height="170dp"
        android:maxHeight="170dp"
        android:scaleType="centerCrop"
        android:paddingLeft="half of your screen width"
        android:paddingBottom="half of your screen height"
        android:adjustViewBounds="true" 
        android:focusable="false"
/>
Run Code Online (Sandbox Code Playgroud)

您可以设置内边距以向左或向右移动图像,也可以设置顶部和底部内边距以向上或向下移动


pax*_*axx 1

由于我没有找到通过 xml(视图)处理这种情况的方法,所以我转向(正如 @serenskye 建议的那样)编写代码。这是我的代码,我希望它有所帮助(ps:我稍微改变了我的逻辑,我想按宽度适合图像,所以我将其缩放到预定义的 imageWidght,然后将其裁剪为 imageHeight)

//bm is received image (type = Bitmap)
Bitmap scaledImage = null;
float scaleFactor = (float) bm.getWidth() / (float) imageWidth;

//if scale factor is 1 then there is no need to scale (it will stay the same)
if (scaleFactor != 1) {
    //calculate new height (with ration preserved) and scale image
    int scaleHeight = (int) (bm.getHeight() / scaleFactor);                     
    scaledImage = Bitmap.createScaledBitmap(bm, imageWidth, scaleHeight, false);
}
else {
    scaledImage = bm;
}

Bitmap cropedImage = null;
//if cropped height is bigger then image height then there is no need to crop
if (scaledImage.getHeight() > imageHeight)
    cropedImage = Bitmap.createBitmap(scaledImage, 0, 0, imageWidth, imageHeight);
else
    cropedImage = scaledImage;

iv.setImageBitmap(cropedImage);
Run Code Online (Sandbox Code Playgroud)