Skip to content Skip to sidebar Skip to footer

How To Centercrop An Image Programatically By Maintaining Aspect Ratio Like Centercrop Do In Xml?

How to centerCrop an image like the same method 'centerCrop' do in xml android ? I don't want to crop the center of the image .I have tried the below code but ,it was cropping the

Solution 1:

If you want to do same effect (exactly same effect), you can watch how Android do it here: https://github.com/android/platform_frameworks_base/blob/3f453164ec884d26a556477027b430cb22a9b7e3/core/java/android/widget/ImageView.java

Interesting part of code about CENTER_CROP:

[...]
mDrawMatrix = mMatrix;

float scale;
float dx = 0, dy = 0;

if (dwidth * vheight > vwidth * dheight) {
    scale = (float) vheight / (float) dheight; 
    dx = (vwidth - dwidth * scale) * 0.5f;
} else {
    scale = (float) vwidth / (float) dwidth;
    dy = (vheight - dheight * scale) * 0.5f;
}

mDrawMatrix.setScale(scale, scale);
mDrawMatrix.postTranslate((int) (dx + 0.5f), (int) (dy + 0.5f));

[...]

Post a Comment for "How To Centercrop An Image Programatically By Maintaining Aspect Ratio Like Centercrop Do In Xml?"