Android系统.从它的资源ID获取图像大小

ale*_*lex 24 resources android image image-size

这是我的活动的一部分:

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);
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用矩阵作为比例类型在ImageView中显示图像(我想稍后添加多点触控).但在用户开始交互之前,我希望图像居中并适合ImageView.我已经找到了解决方法,但是我有一个问题:使用矩阵使图像居中,我需要知道它的宽度和高度.当你所拥有的只是int资源时,有没有办法获得图像大小?

Bla*_*elt 46

使用BitmapFactory.decodeResource获取资源的Bitmap对象,然后从位图中使用getHeightgetWidth轻松检索图像宽度/高度

另外,不要忘记回收您的位图

编辑:

这样您将获得一个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;
Run Code Online (Sandbox Code Playgroud)

  • 你还应该使用`BitmapFactory.Options维=新的BitmapFactory.Options(); dimensions.inJustDecodeBounds = true;`只是解码图像尺寸而不实际将位图加载到内存中. (13认同)

xba*_*esx 11

对于那些没有读过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
Run Code Online (Sandbox Code Playgroud)