Created
July 14, 2016 22:23
-
-
Save jlmalone/281eccaee4c23b85b5cf79ec207cd1b2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.annotation.TargetApi; | |
import android.content.Context; | |
import android.graphics.Matrix; | |
import android.os.Build; | |
import android.util.AttributeSet; | |
import android.widget.ImageView; | |
public class ImageViewTopCrop extends ImageView | |
{ | |
public ImageViewTopCrop(Context context) | |
{ | |
super(context); | |
init(); | |
} | |
public ImageViewTopCrop(Context context, AttributeSet attrs) | |
{ | |
super(context, attrs); | |
init(); | |
} | |
public ImageViewTopCrop(Context context, AttributeSet attrs, int defStyle) | |
{ | |
super(context, attrs, defStyle); | |
init(); | |
} | |
@TargetApi(Build.VERSION_CODES.LOLLIPOP) | |
public ImageViewTopCrop(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { | |
super(context, attrs, defStyleAttr, defStyleRes); | |
init(); | |
} | |
@Override | |
protected boolean setFrame(int left, int top, int right, int bottom) | |
{ | |
if (getDrawable() != null) | |
{ | |
Matrix matrix = getImageMatrix(); | |
int width = right - left; | |
int height = bottom - top; | |
int intrinsicWidth = getDrawable().getIntrinsicWidth(); | |
int intrinsicHeight = getDrawable().getIntrinsicHeight(); | |
float widthScaleFactor = (float) width / (float) intrinsicWidth; | |
float heightScaleFactor = (float) height / (float) intrinsicHeight; | |
float scaleFactor = Math.max(widthScaleFactor, heightScaleFactor); | |
matrix.setScale(scaleFactor, scaleFactor, 0, 0); | |
if (widthScaleFactor < heightScaleFactor) { | |
// if we're going to crop the width, translate the resulting image | |
// so that we crop from the center, equal amounts left and right | |
float targetWidth = intrinsicWidth * scaleFactor; | |
float translateX = (width - targetWidth) / 2.f; | |
matrix.postTranslate(translateX, 0); | |
} | |
setImageMatrix(matrix); | |
} | |
return super.setFrame(left, top, right, bottom); | |
} | |
private void init() { | |
setScaleType(ImageView.ScaleType.MATRIX); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a top center cropping imageview which strangely is not a default option in Android. Many of the normal parameters one could normally apply to an ImageView might not work.