Mallika February 2016

Top crop with ImageLoader - Android

I'm loading images from URLs into my ImageView like so -

ImageLoader.getInstance().displayImage(url, imageview, display-options)

Now I would like to crop the image to the center top. I tried using https://gist.github.com/arriolac/3843346 but I think it expects the image via a drawable and I want to use ImageLoader to set the image.

Can somebody help me understand if I can use https://code.google.com/archive/p/android-query/ (Android Query) in conjunction with ImageLoader?

Is there any way to handle cropping in Android (apart from centerCrop) natively?

Answers


AndroidCoolestRulest February 2016

Replace your ImageView with ProfileImageView and enjoy the view :)

public class ProfileImageView extends ImageView {
private Bitmap bm;

public ProfileImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    bm = null;
}

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    super.onLayout(changed, left, top, right, bottom);
    if (bm != null) {
        setImageBitmap(bm);
        bm = null;
    }
}

@Override
public void setImageBitmap(Bitmap bm) {
    int viewWidth = getWidth();
    int viewHeight = getHeight();
    if (viewWidth == 0 || viewHeight == 0) {
        this.bm = bm;
        return;
    }
    setScaleType(ScaleType.MATRIX);

    Matrix m = getImageMatrix();
    m.reset();
    int min = Math.min(bm.getWidth(), bm.getHeight());
    int cut;
    if (bm.getWidth() > viewWidth && bm.getWidth() > bm.getHeight()) {
        cut = Math.round((bm.getWidth() - viewWidth) / 2.f);
    } else {
        cut = 0;
    }
    RectF drawableRect = new RectF(cut, 0, min - cut, min);

    RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
    m.setRectToRect(drawableRect, viewRect, Matrix.ScaleToFit.START);
    setImageMatrix(m);
    super.setImageBitmap(bm);
}

}

Post Status

Asked in February 2016
Viewed 3,394 times
Voted 5
Answered 1 times

Search




Leave an answer