2013-08-01 119 views
1

我有一个我想要适合高度,保持长宽比。这里是图像:ImageView适合高度保持长宽比

enter image description here

我想红色波段适合的灰排保持其纵横比(ImageView的宽度应增加)的高度。 我已经尝试过在XML中的scaleType属性,但没有任何工作,因为我想要的。

有什么建议吗?

+0

你有没有搜索过? – deadfish

+0

我认为回答你的问题是没有用的。如果你知道如何解决它,请赐教。 –

回答

2

您应该能够改变自定义的ImageView的这样的代码:

  • 保持纵横比
  • 伸展图像时必要的ImageView
  • 作物高度溢出

代码的宽度:

public class ImageViewScaleTypeTopCrop extends ImageView { 
    public ImageViewScaleTypeTopCrop(Context context) { 
     super(context); 
     setup(); 
    } 

    public ImageViewScaleTypeTopCrop(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     setup(); 
    } 

    public ImageViewScaleTypeTopCrop(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     setup(); 
    } 

    private void setup() { 
     setScaleType(ScaleType.MATRIX); 
    } 

    @Override 
    protected boolean setFrame(int frameLeft, int frameTop, int frameRight, int frameBottom) { 

     float frameWidth = frameRight - frameLeft; 
     float frameHeight = frameBottom - frameTop; 

     if (getDrawable() != null) { 

      Matrix matrix = getImageMatrix(); 
      float scaleFactor, scaleFactorWidth, scaleFactorHeight; 

      scaleFactorWidth = (float) frameWidth/(float) getDrawable().getIntrinsicWidth(); 
      scaleFactorHeight = (float) frameHeight/(float) getDrawable().getIntrinsicHeight(); 

      if (scaleFactorHeight > scaleFactorWidth) { 
       scaleFactor = scaleFactorHeight; 
      } else { 
       scaleFactor = scaleFactorWidth; 
      } 

      matrix.setScale(scaleFactor, scaleFactor, 0, 0); 
      setImageMatrix(matrix); 
     } 

     return super.setFrame(frameLeft, frameTop, frameRight, frameBottom); 
    } 

} 
相关问题