Android系统。获取图像大小从它的资源ID [英] Android. Obtaining image size from it's resource id

查看:112
本文介绍了Android系统。获取图像大小从它的资源ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的活动的一部分:

This is a part of my Activity:

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资源

I try to display an image within an ImageView using a matrix as scale type (I want to add multitouch later). But before user starts interaction i want the image to be centered and fit inside the ImageView. I already found answers concerning how to solve it but there is one problem for me: to make image centered using matrix I need to know its width and height. Is there any way of getting image size when all you have is int resource ?

推荐答案

使用<一个href="http://developer.android.com/reference/android/graphics/BitmapFactory.html#de$c$cResource%28android.content.res.Resources,%20int%29">BitmapFactory.de$c$cResource以获得该资源的一个位图对象,然后从位图可以很容易地检索图像宽度/高度与<一href="http://developer.android.com/reference/android/graphics/Bitmap.html#getHeight%28%29">getHeight和<一href="http://developer.android.com/reference/android/graphics/Bitmap.html#getWidth%28%29">getWidth

Use BitmapFactory.decodeResource to obtain a Bitmap object of the resource, and then from the bitmap you can easily retrieve the image width/height with getHeight and getWidth

另外不要忘了回收位图

编辑:

此方式,您将得到一个位图作为输出,但BitmapFactory.Options将与同和高度的位图进行设置。所以,在这种情况下,,则不需要回收该位图

This way you will get a null bitmap as output, but the BitmapFactory.Options will be set with the with and height for the bitmap. So, in this case,, you do not need to recycle the bitmap

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;

这篇关于Android系统。获取图像大小从它的资源ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆