2015-04-02 170 views
0

我计算出我的片段的宽度和高度,并将其图像缩放到该片段的特定百分比。这适用于需要按比例放大以符合该尺寸的图像,但较大的图像似乎忽略了比例(我认为它们会缩小一点但不会缩小比例)。为什么图像大于设置的大小没有缩小

我通过http asyncTask调用获取我的图像然后onPostexecute设置imageView控件src并缩放imageView。为更小的图像工作,而不是更大的图像。

较大的图像是10kb,较小的是1kb。

protected void onPostExecute(Bitmap result) { 
     bmImage.setImageBitmap(result); 
     if (result != null) { 
      int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PT, 35, getContext().getResources().getDisplayMetrics()); 
      int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PT, 35, getContext().getResources().getDisplayMetrics()); 

      bmImage.setMinimumWidth(width); 
      bmImage.setMinimumHeight(height); 
      bmImage.setMaxWidth(width); 
      bmImage.setMaxHeight(height); 

     } 

我看到的尺寸是calc'c正确,并在事后ImageView的正确设置)(最小和maxheight),但mDrawable attr为大所以也许这是拨错ATTR设定的指标?

+0

您需要使用自定义的ImageView。你的图片是长方形的吗? – Ajeet 2015-04-02 09:13:06

+0

是的,他们是透明背景的PNG,使它看起来像是不同的形状。为什么会忽略setMaxHeight而不是SetMinimumHeight? – Fearghal 2015-04-02 09:45:39

+0

整洁的解决方案粘贴,工作一种享受,它包装在一个类,以启动:) – Fearghal 2015-04-02 10:12:19

回答

0

https://argillander.wordpress.com/2011/11/24/scale-image-into-imageview-then-resize-imageview-to-match-the-image/

private void scaleImage(ImageView view, int boundBoxInDp) 
{ 
    // Get the ImageView and its bitmap 
    Drawable drawing = view.getDrawable(); 
    Bitmap bitmap = ((BitmapDrawable)drawing).getBitmap(); 

    // Get current dimensions 
    int width = bitmap.getWidth(); 
    int height = bitmap.getHeight(); 

    // Determine how much to scale: the dimension requiring less scaling is 
    // closer to the its side. This way the image always stays inside your 
    // bounding box AND either x/y axis touches it. 
    float xScale = ((float) boundBoxInDp)/width; 
    float yScale = ((float) boundBoxInDp)/height; 
    float scale = (xScale <= yScale) ? xScale : yScale; 

    // Create a matrix for the scaling and add the scaling data 
    Matrix matrix = new Matrix(); 
    matrix.postScale(scale, scale); 

    // Create a new bitmap and convert it to a format understood by the ImageView 
    Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); 
    BitmapDrawable result = new BitmapDrawable(scaledBitmap); 
    width = scaledBitmap.getWidth(); 
    height = scaledBitmap.getHeight(); 

    // Apply the scaled bitmap 
    view.setImageDrawable(result); 

    // Now change ImageView's dimensions to match the scaled image 
    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams(); 
    params.width = width; 
    params.height = height; 
    view.setLayoutParams(params); 
}