【问题标题】:Android. Obtaining image size from it's resource id安卓。从其资源 id 获取图像大小
【发布时间】:2012-03-28 04:07:11
【问题描述】:

这是我活动的一部分:

private ImageView mImageView;
private int resource;

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  resource = getIntent().getIntExtra("res", -1);

  Matrix initMatrix = new Matrix();

  mImageView = new ImageView(getApplicationContext());
  mImageView.setScaleType( ImageView.ScaleType.MATRIX );
  mImageView.setImageMatrix( initMatrix );
  mImageView.setBackgroundColor(0);
  mImageView.setImageResource(resource);
}

我尝试使用矩阵作为比例类型在 ImageView 中显示图像(我想稍后添加多点触控)。但在用户开始交互之前,我希望图像居中并适合 ImageView。 我已经找到了有关如何解决它的答案,但对我来说有一个问题: 要使用矩阵使图像居中,我需要知道它的宽度和高度。当您只有 int 资源 时,有什么方法可以获取图像大小?

【问题讨论】:

    标签: android image resources image-size


    【解决方案1】:

    使用BitmapFactory.decodeResource获取资源的Bitmap对象,然后通过getHeightgetWidth从位图中轻松获取图片的宽/高

    别忘了recycle你的位图

    编辑:

    这样您将获得一个null 位图作为输出,但BitmapFactory.Options 将设置位图的with 和height。因此,在这种情况下,您不需要回收位图

    BitmapFactory.Options dimensions = new BitmapFactory.Options(); 
    dimensions.inJustDecodeBounds = true;
    Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bitmap, dimensions);
    int height = dimensions.outHeight;
    int width =  dimensions.outWidth;
    

    【讨论】:

    • 您还应该使用BitmapFactory.Options dimensions = new BitmapFactory.Options(); dimensions.inJustDecodeBounds = true; 来解码图像尺寸,而无需实际将位图加载到内存中。
    • 对我来说,如果我设置 inJustDecodeBounds = true,为什么 mBitmap 会为空?如果我将它设置为 false,它会返回一个位图。
    • @Ankit 这是正常行为,在文档中有描述
    • @Ankit 感谢指出,这是一个错误。我已经更新了我的答案
    • @blackbelt,很好的答案,应该提到,在您编辑之后,您也不需要回收位图(因为您没有得到一个)。
    【解决方案2】:

    对于没有阅读 dmon 评论的任何人。执行此操作的代码如下所示:

    final Options opt = new BitmapFactory.Options();
    opt.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(getResources(), R.drawable.your_photo, opt);
    
    opt.outHeight; // height of resource
    opt.outWidth; // width of resource
    

    【讨论】:

    • 你的意思是BitmapFactory.decodeResource(getResources(), R.drawable.your_photo, opt);
    • 感谢@xbakesx 最佳解决方案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多