我正在尝试同时缩放和裁剪图像,并从左到右的屏幕边缘显示它。我收到的图像比用户屏幕稍微宽一些,我可以像这样扩展它(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”
答案 0 :(得分:3)
<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"
/>
您可以设置填充以向左或向右移动图像,也可以设置顶部和底部填充以上下移动
答案 1 :(得分: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);
答案 2 :(得分:0)
添加
android:layout_gravity="center"