2

I have two images that don't always completely fit onto the screen. Therefore I want to crop them (like CENTER_CROP does) but in a way, so that the bottom area of the image is always visible. Both images fill the entire screen width and each 1/2 of the screen height.

I found a similar solution here: ImageView scaling TOP_CROP The accepted solution works perfectly, but I can't figure out how to change the matrix to make it BOTTOM_CROP instead.

Working Code for TOP_CROP:

setScaleType(ScaleType.MATRIX);
Matrix matrix = getImageMatrix();
float scaleFactor = (getWidth() - Data.getImgPadding(c)) / (float) getDrawable().getIntrinsicWidth();
matrix.setScale(scaleFactor, scaleFactor, 0, 0);
setImageMatrix(matrix);

Note: A padding to the right is set programmatically, therefore it needs to be included in the calculation (the value is read by Data.getImgPadding(c)).

For BOTTOM_CROP I thought I'd use:

matrix.setScale(scaleFactor, scaleFactor, 0, getHeight());

But it's not really working, for the first image the bottom part is displayed more or less correctly, but there is some sort of margin below it - the bottom image border should be exactly at the bottom ImageView border. I assume I have to use the padding somehow but I don't know how to caculate the "new" image height after the horizontal padding value is set.

The bigger problem however is that (for whatever reason) when I set the value py in setScale() the second ImageView is suddenly empty... both views use the same layout xml, but that can't be the reason as the original code works perfectly on both.

Community
  • 1
  • 1
Diana
  • 75
  • 1
  • 9

1 Answers1

2

I know this is a long time gone, but I've modified the answer in the post to suit your need.

@Override
protected boolean setFrame(int l, int t, int r, int b) {
    boolean hasChanged = super.setFrame(l, t, r, b);
    Matrix matrix = getImageMatrix();
    float scaleFactor = getWidth() / (float) getDrawable().getIntrinsicWidth();
    matrix.setScale(scaleFactor, scaleFactor, 0, 0);

    // The Important Bit
    Drawable drawable = getDrawable();
    float heightD = drawable.getIntrinsicHeight();
    float height = getHeight();
    matrix.setTranslate(0, height - heightD);

    setImageMatrix(matrix);
    return hasChanged;
}

Hope it helps!

SalicBlu3
  • 1,874
  • 2
  • 19
  • 32