25

这是我活动的一部分:

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 资源时,有什么方法可以获取图像大小?

4

2 回答 2

49

使用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;
于 2012-03-11T14:15:48.210 回答
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
于 2012-08-03T13:50:28.233 回答