Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android XML中的图像缩放和裁剪_Android_Android Layout_Android Imageview - Fatal编程技术网

Android XML中的图像缩放和裁剪

Android XML中的图像缩放和裁剪,android,android-layout,android-imageview,Android,Android Layout,Android Imageview,我试图同时缩放和裁剪图像,并从屏幕的左至右边缘显示它。我接收到的图像仅比用户屏幕宽一点点,我可以像这样缩放它(XML): 但我得到的是: 我想将图像对齐到右上角,如下所示: 这可能吗?我尝试了所有的缩放类型,但没有发现效果,图像要么按X和Y进行缩放(fitXY,fitStart),要么裁剪图像但居中(centerCrop)。我需要像android:scaleType=“cropStart”这样的东西,因为我没有找到通过xml(视图)来处理这种情况的方法,所以我转向(正如@serensky

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


但我得到的是:

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


这可能吗?我尝试了所有的缩放类型,但没有发现效果,图像要么按X和Y进行缩放(fitXY,fitStart),要么裁剪图像但居中(centerCrop)。我需要像android:scaleType=“cropStart”

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


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

android:layout_gravity="center"

在设置映像之前,使用代码比使用xml更容易,这样您就可以进行更细粒度的控制是的,代码是我的选项b。但对我来说很奇怪的是,这是一个无法解决的问题(至少我不能:)。如果您可以选择适合有关star的图像,为什么不能在开始时裁剪图像?
android:scaleType=“centerCrop”
是我的解决方案,谢谢!
//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"
/>
android:layout_gravity="center"