Skip to content

Instantly share code, notes, and snippets.

@ohmrefresh
Last active August 29, 2015 14:03
Show Gist options
  • Save ohmrefresh/32df78d7a9f2013d91ef to your computer and use it in GitHub Desktop.
Save ohmrefresh/32df78d7a9f2013d91ef to your computer and use it in GitHub Desktop.
TopCropImageView
import android.content.Context;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.widget.ImageView;
public class TopCropImageView extends ImageView {
public TopCropImageView(Context context, AttributeSet attrs) {
super(context, attrs);
setScaleType(ScaleType.MATRIX);
}
public TopCropImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setScaleType(ScaleType.MATRIX);
}
public TopCropImageView(Context context) {
super(context);
setScaleType(ScaleType.MATRIX);
}
@Override
protected boolean setFrame(int l, int t, int r, int b)
{
if (getDrawable() == null) {
return super.setFrame(l, t, r, b);
}
Matrix matrix = getImageMatrix();
float scaleWidth = getWidth()/(float)getDrawable().getIntrinsicWidth();
float scaleHeight = getHeight()/(float)getDrawable().getIntrinsicHeight();
float scaleFactor = (scaleWidth > scaleHeight) ? scaleWidth : scaleHeight;
matrix.setScale(scaleFactor, scaleFactor, 0, 0);
if (scaleFactor == scaleHeight) {
float tanslateX = ((getDrawable().getIntrinsicWidth() * scaleFactor) - getWidth()) / 2;
matrix.postTranslate(-tanslateX, 0);
}
setImageMatrix(matrix);
return super.setFrame(l, t, r, b);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment