Create a gist now

Instantly share code, notes, and snippets.

Custom Android ImageView for top-crop scaling of the contained drawable.
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.ImageView;
/**
* Created by chris on 7/27/16.
*/
public class TopCropImageView extends ImageView {
public TopCropImageView(Context context) {
super(context);
init();
}
public TopCropImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public TopCropImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public TopCropImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
recomputeImgMatrix();
}
@Override
protected boolean setFrame(int l, int t, int r, int b) {
recomputeImgMatrix();
return super.setFrame(l, t, r, b);
}
private void init() {
setScaleType(ScaleType.MATRIX);
}
private void recomputeImgMatrix() {
final Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
final Matrix matrix = getImageMatrix();
float scale;
final int viewWidth = getWidth() - getPaddingLeft() - getPaddingRight();
final int viewHeight = getHeight() - getPaddingTop() - getPaddingBottom();
final int drawableWidth = drawable.getIntrinsicWidth();
final int drawableHeight = drawable.getIntrinsicHeight();
if (drawableWidth * viewHeight > drawableHeight * viewWidth) {
scale = (float) viewHeight / (float) drawableHeight;
} else {
scale = (float) viewWidth / (float) drawableWidth;
}
matrix.setScale(scale, scale);
setImageMatrix(matrix);
}
}
@Wavesonics

Great snippet, works perfectly!

@suda
suda commented Jan 14, 2013

Looks like it's missing

import android.content.Context;

import :)

@arriolac
Owner

@suda, thanks!

@idnael
idnael commented May 17, 2013

your soluton worked for me until I change the device orientation!
Then setFrame is called with the previous view width value.
SO I think maybe I should put the change matrix code in another method?

@gbenson-nflx

This was helpful but I also had to override onLayout() to get the scaling matrix to update properly for layout changes. Using setFrame() was not enough given my usage.

e.g.:

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        recomputeImgMatrix();
    }
@ErNaveen

need imageview with zoom in and out with croping can i use it

@followztx

@gbenson-nflx thanks .

@enknamel
enknamel commented Feb 2, 2015

@gbenson-nflx My images were not showing up at all until I added your code. Very strange. Though I am using this as a background for a layout in a scrollview so something wonky is going on.

@cesards
cesards commented Feb 17, 2015

I developed a library for this purpose. I think it's a litte bit late but you could add the dependency and replace it ;-)

https://github.com/cesards/CropImageView

Have fun!!

@arriolac
Owner

@gbenson-nflx updated the gist from the snippet you shared. Thanks!

@zelin
zelin commented Apr 8, 2015

Great snippet ^^

@adriancosma

I would like to have the imageview crop the top center part of the image, now seems that is top left. How can I change the code to obtain a crop centered and not left aligned? Thanks!

@briandilley

to center it:

    private void recomputeImgMatrix() {
        final Matrix matrix = getImageMatrix();

        float scale;
        final int viewWidth = getWidth() - getPaddingLeft() - getPaddingRight();
        final int viewHeight = getHeight() - getPaddingTop() - getPaddingBottom();
        final int drawableWidth = getDrawable().getIntrinsicWidth();
        final int drawableHeight = getDrawable().getIntrinsicHeight();

        if (drawableWidth * viewHeight > drawableHeight * viewWidth) {
            scale = (float) viewHeight / (float) drawableHeight;
        } else {
            scale = (float) viewWidth / (float) drawableWidth;
        }

        matrix.setScale(scale, scale);
        if ((drawableWidth * scale) > viewWidth) {
            float tr = -(((drawableWidth * scale) - viewWidth) / 2);
            matrix.postTranslate(tr, 0);
        }
        setImageMatrix(matrix);
    }
@Bapho
Bapho commented Aug 11, 2015

be aware that the drawable can be null in recomputeImgMatrix().

@OMID9191

hi:
i import this class to my project ...
how to use for another class and use for image view ?

@OMID9191

pls any tell me

@spartacus777

Worked perfectly in conjunction with UIL (universal image loader)

@cesards
cesards commented Oct 20, 2015

This snippet has a bug in devices with API < 16

I recommend use my lib. It`s already fixed:

here

@nv95
nv95 commented Oct 23, 2015

Thanks! But it's will be better for using in xml with additional constructors:

    public TopCropImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setScaleType(ScaleType.MATRIX);
    }

    public TopCropImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setScaleType(ScaleType.MATRIX);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public TopCropImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        setScaleType(ScaleType.MATRIX);
    }
@MrVilkaman

to left side add matrix.postTranslate(viewWidth - drawableWidth*scale,0); after matrix.setScale(scale, scale);

@naeimrezaeian

when i use this class compile show this error
android.view.InflateException: Binary XML file

@jrh4016
jrh4016 commented Apr 14, 2016

I'd love to get an explanation on how to use this in detail.

I've created a new file with this name and copied over the code. I then changed my ImageView to a TopCropImageView in XML, but I'm getting a litany of errors
Custom view TopCropImageView is not using the 2- or 3-argument View constructors; XML attributes will not work
java.lang.NullPointerException at line 35
Unable to start activity... android.view.InflateException: Binary XML file line #62: Binary XML file line #62: Error inflating class

@Firsto
Firsto commented Apr 18, 2016

add this code

@barakhadar

First, great stuff! It works great! But, there's a but.. What I'm looking for is exactly the opposite...
How do I modify the code so that I'll have the same effect, but with the bottom of my image rather that it's top (as it works by default) ?

@barakhadar

Never mind... Thanks to @MrVilkaman answer, I found the way.. Thanks dude!

So what you'll do to accomplish that, simply add at the bottom of the class, right after matrix.setScale(scale, scale);, this line : matrix.postTranslate( 0, viewHeight - drawableHeight * scale);.

Hope it will help someone else too..
Cheers!

@arriolac
Owner

It's been a while since I've updated this class which explains why there's some issues/warnings caused by newer APIs. I'll be posting an update to this code soon.

@arriolac
Owner

Updated gist to now work when inflated in XML and making sure that the drawable is not null before using it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment