4

我正在尝试同时缩放和裁剪图像并从左到右屏幕边缘显示它。我收到的图像比用户屏幕宽一点,我可以像这样缩放它(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"
        />

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

我想像这样将图像对齐到右上角: 我想要的是

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

4

3 回答 3

4
<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"
/>

您可以设置填充以向左或向右移动图像,也可以设置上下填充以上下移动

于 2013-12-28T07:01:21.227 回答
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);
于 2013-02-21T09:38:43.530 回答
0

添加

android:layout_gravity="center"
于 2021-03-08T11:36:03.570 回答