在XML中缩放和裁剪图像

5

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

在设置图像之前,用代码来完成可能比使用XML更容易,这样你就可以拥有更精细的控制。 - serenskye
是的,代码是我的选择。但对我来说,这是一件无法在视图中解决的奇怪的事情(至少我不能)。如果您有关于星形的图像适配选项,为什么不能裁剪星形图片呢? - paxx
3个回答

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

你可以设置内边距来将图片向左或向右移动,同时通过上下内边距来进行上下移动。


android:scaleType="centerCrop" 是我的解决方案,谢谢! - Eido95

1

由于我没有找到通过xml(视图)处理这种情况的方法,所以我转向了代码(正如@serenskye建议的那样)。这是我的代码,希望它有所帮助(附注:我已经稍微改变了我的逻辑,我想按宽度适配图片,所以我将其缩放到预定义的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);

0

增加

android:layout_gravity="center"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接