【问题标题】:Scale and crop image in XML在 XML 中缩放和裁剪图像
【发布时间】:2013-02-18 13:56:28
【问题描述】:

我正在尝试同时缩放和裁剪图像,并从左到右屏幕边缘显示它。我收到的图像比用户屏幕宽一点,我可以像这样缩放它(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 更容易,然后您将拥有更细粒度的控制
  • 是的,代码是我的选择 b。但令我感到奇怪的是,这是无法解决的问题(至少我不能:))。如果您可以选择适合明星的图像,为什么不能在开始时裁剪图像?

标签: android android-layout android-imageview


【解决方案1】:
<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" 是我的解决方案,谢谢!
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    添加

    android:layout_gravity="center"
    

    【讨论】:

      猜你喜欢
      • 2017-06-18
      • 1970-01-01
      • 1970-01-01
      • 2012-07-21
      • 2015-04-20
      • 1970-01-01
      • 2011-11-16
      • 2016-08-29
      • 1970-01-01
      相关资源
      最近更新 更多