Created
December 7, 2015 23:05
-
-
Save suclike/a959fd709b069322cc6d to your computer and use it in GitHub Desktop.
This file contains hidden or 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.content.Context; | |
import android.graphics.Matrix; | |
import android.util.AttributeSet; | |
import android.widget.ImageView; | |
public class TopImageCrop extends ImageView { | |
public TopImageCrop(final Context context) { | |
super(context); | |
init(); | |
} | |
public TopImageCrop(final Context context, final AttributeSet attrs) { | |
super(context, attrs); | |
init(); | |
} | |
public TopImageCrop(final Context context, final AttributeSet attrs, final int defStyle) { | |
super(context, attrs, defStyle); | |
init(); | |
} | |
private void init() { | |
setScaleType(ImageView.ScaleType.MATRIX); | |
} | |
@Override | |
protected boolean setFrame(final int frameLeft, final int frameTop, final int frameRight, final int frameBottom) { | |
float frameWidth = frameRight - frameLeft; | |
float frameHeight = frameBottom - frameTop; | |
float originalImageWidth = (float) getDrawable().getIntrinsicWidth(); | |
float originalImageHeight = (float) getDrawable().getIntrinsicHeight(); | |
float usedScaleFactor = 1; | |
if ((originalImageWidth > frameWidth) || (originalImageHeight > frameHeight)) { | |
// If frame is bigger than image | |
// => Crop it, keep aspect ratio and position it at the bottom and center horizontally | |
float fitHorizontallyScaleFactor = frameWidth / originalImageWidth; | |
float fitVerticallyScaleFactor = frameHeight / originalImageHeight; | |
usedScaleFactor = Math.max(fitHorizontallyScaleFactor, fitVerticallyScaleFactor); | |
} | |
float newImageWidth = originalImageWidth * usedScaleFactor; | |
float newImageHeight = originalImageHeight * usedScaleFactor; | |
Matrix matrix = getImageMatrix(); | |
matrix.setScale(usedScaleFactor, usedScaleFactor, 0, 0); // Replaces the old matrix completly | |
matrix.postTranslate((frameWidth - newImageWidth) / 2, frameHeight - newImageHeight); | |
setImageMatrix(matrix); | |
return super.setFrame(frameLeft, frameTop, frameRight, frameBottom); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use with ContextCompat.getDrawable(context, R.drawable.resource)