XML中的缩放和裁剪图像

问题描述:

我试图同时缩放和裁剪图像,并从左到右的屏幕边缘显示它。我收到的图像比用户屏幕宽只是点点,我能够扩展它像这样(XML):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" 
     /> 

但是,这是我所得到的: What I get

我想像这样对齐右上角的图像: What I want

这可能吗?我已经尝试过所有scaleType,但注意到了作品,图像被缩放以适合X和Y(fitXY,fitStart)或图像裁剪但居中(centerCrop)。我需要像android一样的东西:scaleType =“cropStart”

+0

可能更容易做到这一点的代码比XML您设定的图像之前,那么你就必须更细粒度的控制 – serenskye 2013-02-18 13:58:42

+0

是的,代码是我的选择b。但对我来说这很奇怪,这是无法解决的问题(至少我不能:))。如果您有选择适合关于明星的图像,为什么不能在开始时裁剪图像? – paxx 2013-02-18 14:04:17

因为我没有找到通过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); 

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

您可以设置填充移动图像向左或向右,也顶部和底部填充到上下移动

+0

'android:scaleType =“centerCrop”'是我的解决方案,谢谢! – Eido95 2017-07-07 23:54:52