1

我可能有不同的drawables(大或小),我总是跨越宽度(match_parent)并按比例增加或减少高度。保持比例。如何按比例缩放宽度等于“match_parent”的任何图像(imageview)?

这怎么可能?

我试着用:

<ImageView 
      android:id="@+id/iv_TEST" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
android:adjustViewBounds="true" 
      android:scaleType="fitXY" 
      android:src="@drawable/test" /> 

的问题是,它增加或减少的宽度,它看起来不错。

enter image description here

+1

使用'机器人:scaleType = “fitStart”',看看结果是你在找什么。 – hardartcore

+0

你必须获得'ImageView'的父视图的宽度,因此你可以确定缩放因子。之后你可以得到可缩放的可绘画并设置它。 –

+0

它不起作用,图像不被拉伸以填充整个宽度 – ephramd

回答

11

固定。要解决此问题,你需要做的:

  1. 自定义的ImageView
  2. 设置可绘制到"android:src",从代码(imageview.setImageResource()

通过ResizableImageView更换的ImageView:

<"the name of your package".ResizableImageView 
      android:id="@+id/iv_test" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      /> 

ResizableImageView .class

public class ResizableImageView extends ImageView { 
     public ResizableImageView(Context context, AttributeSet attrs) { 
      super(context, attrs); 
     } 

     public ResizableImageView(Context context) { 
      super(context); 
     } 

     @Override 
     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
      Drawable d = getDrawable(); 
      if (d == null) { 
       super.setMeasuredDimension(widthMeasureSpec, heightMeasureSpec); 
       return; 
      } 

      int imageHeight = d.getIntrinsicHeight(); 
      int imageWidth = d.getIntrinsicWidth(); 

      int widthSize = MeasureSpec.getSize(widthMeasureSpec); 
      int heightSize = MeasureSpec.getSize(heightMeasureSpec); 

      float imageRatio = 0.0F; 
      if (imageHeight > 0) { 
       imageRatio = imageWidth/imageHeight; 
      } 
      float sizeRatio = 0.0F; 
      if (heightSize > 0) { 
       sizeRatio = widthSize/heightSize; 
      } 

      int width; 
      int height; 
      if (imageRatio >= sizeRatio) { 
       // set width to maximum allowed 
       width = widthSize; 
       // scale height 
       height = width * imageHeight/imageWidth; 
      } else { 
       // set height to maximum allowed 
       height = heightSize; 
       // scale width 
       width = height * imageWidth/imageHeight; 
      } 

      setMeasuredDimension(width, height); 
     } 
    } 

解决方案:I need to size the imageView inside my table row programatically

相关问题