我在线性布局上有一个图像视图。
我希望图像视图能够缩放它所持有的位图,因此它在线性布局中占用最大空间,但仍保持适当的图像比例。
  public static void sharedUtilScaleImage(ImageView view)
  {
      Drawable drawing = view.getDrawable();
      //--
      Bitmap bitmap = ((BitmapDrawable)drawing).getBitmap();
      int bitmapWidth = bitmap.getWidth();
      int bitmapHeight = bitmap.getHeight();
      int widthParent = view.getWidth();      
      int heightParent = view.getHeight();      
      //--
      float density = 1;
      if (true) {
        density = MicApp.getContext().getResources().getDisplayMetrics().density;
      }
      //--
      float xScale = ((float) widthParent * density) / bitmapWidth; 
      float yScale = ((float) heightParent * density) / bitmapHeight;
      float minScale = Math.min(xScale, yScale);  
      //-- 
      Matrix matrix = new Matrix();
      matrix.postScale(minScale, minScale);
      //--
      Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, true);
      BitmapDrawable result = new BitmapDrawable(scaledBitmap);
      view.setImageDrawable(result);      
  }
作为参考,我在这里找到了上面的一些代码:http://stackoverflow.com/questions/8114085/how-to-create-white-border-around-bitmap
但是,我觉得上面有点令人费解。
- 我将所有位图存储在 drawable-hdpi
 - 位图 .getHeight/.getWidth 返回实际像素(而不是密度改变的像素)
 - 但是视图 .getHeight / .getWidth 返回的像素小于手机上的实际像素使用量。我需要将它们与密度相乘以获得实际像素。
 
为什么返回值的差异?
我喜欢我的位图返回它们的实际像素大小。但是我在其他地方读到需要将它们放在“res/drawable-nodpi”中,所以这似乎是一个额外的不一致?
作为参考,将位图放置在 imageview 中的代码,以及线性布局内的 imageview 如下所示:
imageView.setImageResource(picIDs[position]);                       
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);        
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);        
imageView.setLayoutParams(lp);                
//--
linearLayoutInner.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
linearLayoutInner.addView(imageView);