title: How to scale imageview / bitmap and pixels versus dips
body: <p>I have an imageview on a linearlayout.</p>
  
  <p>I would like the imageview to scale the bitmap it holds, so it takes max amount of space in the linear layout, but still keeps proper image scale.</p>
  
  <pre><code>  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);      
    }
  </code></pre>
  
  <p>For reference, I found some of above code here:
  htttp://stackoverflow.com/questions/8114085/how-to-create-white-border-around-bitmap</p>
  
  <p>However, I find above a bit puzzling.</p>
  
  <ul>
  <li>I store all my bitmaps in drawable-hdpi</li>
  <li>The bitmap .getHeight/.getWidth returns the actual pixels (and not density altered pixels)</li>
  <li>however the view .getHeight / .getWidth returns pixels that are smaller than their actual pixel usage on the phone. I need to multiply them with density to get the actual pixels.</li>
  </ul>
  
  <p>Why the difference in values returned? </p>
  
  <p>I like my bitmaps return their actual pixel size. But I read elsewhere that would require them to be placed in "res/drawable-nodpi", so that seems like an additional inconsistency? </p>
  
  <p>For reference the code that places bitmap in imageview, and imageview inside linear layout looks like this:</p>
  
  <pre><code>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);       
  </code></pre>