Last active
December 31, 2015 13:59
-
-
Save Jpoliachik/7997568 to your computer and use it in GitHub Desktop.
For Android:A subclass of ImageView that scales the image as 'TopCrop' The source image will be scaled to match the view and cropped so the top of the image remains fixed at the top of the view. The bottom will crop according to the view height.
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
/** | |
* @author Justin Poliachik | |
* | |
* This ImageView subclass allows a scale type of 'TopCrop' | |
* The src image will be scaled to match the view and cropped | |
* so that the top of the image remains fixed. | |
* The bottom will crop according to the view height. | |
*/ | |
public class TopCropImage extends ImageView{ | |
public TopCropImage(Context context) { | |
super(context); | |
setup(); | |
} | |
public TopCropImage(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
setup(); | |
} | |
public TopCropImage(Context context, AttributeSet attrs, | |
int defStyle) { | |
super(context, attrs, defStyle); | |
setup(); | |
} | |
private void setup() { | |
setScaleType(ScaleType.MATRIX); | |
} | |
@Override | |
protected boolean setFrame(int l, int t, int r, int b) { | |
Matrix matrix = getImageMatrix(); | |
float scale; | |
int viewWidth = getWidth() - getPaddingLeft() - getPaddingRight(); | |
int viewHeight = getHeight() - getPaddingTop() - getPaddingBottom(); | |
int drawableWidth = getDrawable().getIntrinsicWidth(); | |
int drawableHeight = getDrawable().getIntrinsicHeight(); | |
//Get the scale | |
if (drawableWidth * viewHeight > drawableHeight * viewWidth) { | |
scale = (float) viewHeight / (float) drawableHeight; | |
} else { | |
scale = (float) viewWidth / (float) drawableWidth; | |
} | |
//Define the rect to take image portion from | |
RectF drawableRect = new RectF(0, 0, drawableWidth, drawableHeight - (viewHeight / scale)); | |
RectF viewRect = new RectF(0, 0, viewWidth, viewHeight); | |
matrix.setRectToRect(drawableRect, viewRect, Matrix.ScaleToFit.FILL); | |
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