【问题标题】:ImageView dimensions图像视图尺寸
【发布时间】:2015-12-26 16:35:24
【问题描述】:

我有以下情况

里面有ImageViewBitmap

问题是这样的

  • 我不知道位图的尺寸(不是物理尺寸,它在屏幕上的尺寸)

  • 我需要 ImageView 不能比屏幕上的 Bitmap 大。

ImageView的背景在下面的快照上是黑色的。

【问题讨论】:

  • 你知道Bitmap的screenWidth和长宽比。所以你可以在屏幕上获得位图的大小。
  • @tinysunlight,感谢您的快速答复。能具体解释一下吗?
  • 你的 bitmap 和 imageview 是从哪里来的?如果你只是想剪辑 bitmap,我认为使用第三方库更好。
  • 位图来自相机意图。我认为该解决方案是如此接近,但找不到它
  • 原始位图尺寸是960x1260.screenWidth是900.所以位图在屏幕上的尺寸是900x (900*960/1260)

标签: android android-layout bitmap android-image dimensions


【解决方案1】:

您可以通过在其 xml 文件中的 imageView 标记上将其 layout_width 和 layout_height 设置为 wrap_content 来确保图像视图不大于位图。

您还可以使用它的 scaleType 来影响应如何操作图像以适应 imageView。

您也可以只访问位图的宽度/高度属性来获取其尺寸。

编辑::

您可以将位图转换为 byte[] 并使用以下帮助器调整其大小:

/**
 * Resize an image to a specified width and height.
 * @param targetWidth The width to resize to.
 * @param targetHeight The height to resize to.
 * @return The resized image as a Bitmap.
 * */
public static Bitmap resizeImage(byte[] imageData, int targetWidth, int targetHeight) {
    BitmapFactory.Options options = new BitmapFactory.Options();

    options.inSampleSize = calculateInSampleSize(options, targetWidth, targetHeight);
    options.inJustDecodeBounds = false;

    Bitmap reducedBitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length, options);
    return Bitmap.createScaledBitmap(reducedBitmap, targetWidth, targetHeight, false);
}

private static int calculateInSampleSize(BitmapFactory.Options options, int requestedWidth, int requestedHeight) {
    // Get the image's raw dimensions
    final int rawHeight = options.outHeight;
    final int rawWidth = options.outWidth;

    int inSampleSize = 1;
    if (rawHeight > requestedHeight || rawWidth > requestedWidth) {
        final int halfHeight = rawHeight / 2;
        final int halfWidth = rawWidth / 2;

        /*
        * Calculate the largest inSampleSize value that is a power of 2 and keeps both
        * height and width larger than their requested counterparts respectively.
        * */
        while ((halfHeight/inSampleSize) > requestedHeight && (halfWidth/inSampleSize) > requestedWidth) {
            inSampleSize *= 2;
        }
    }
    return inSampleSize;
}

【讨论】:

  • 谢谢,但我的 ImageView 高度和宽度在 wrap_content;我不想使用 scaleType 因为它会使位图变形。问题是原始位图大小为 960x1260。显然,位图不会在屏幕上填充这个尺寸(
  • 注意并更新了答案,以显示将位图调整为指定尺寸的方法。如果它不能满足您的使用要求,那么一定要查看一些相关的第三方库,比如小太阳说的。我个人使用毕加索来处理位图转换。
猜你喜欢
  • 1970-01-01
  • 2017-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多