How to centerCrop an image Programatically by maintaining Aspect ratio like centerCrop do in XML?

六月ゝ 毕业季﹏ 提交于 2020-01-07 08:47:11

问题


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 center portion of the image,and it produce a square shaped image,I want the same centerCrop function to use in a Canvas on android.Can anyone help?? Hope my question is clear to you.

 Bitmap bitmap=BitmapFactory.decodeResource(res, (R.drawable.ice));
        Bitmap cropBmp;
        if (bitmap.getWidth() >= bitmap.getHeight()){

            cropBmp = Bitmap.createBitmap(
                    bitmap,
                    bitmap.getWidth()/2 - bitmap.getHeight()/2,
                    0,
                    bitmap.getHeight(),
                    bitmap.getHeight()
            );

        }else{

            cropBmp = Bitmap.createBitmap(
                    bitmap,
                    0,
                    bitmap.getHeight()/2 - bitmap.getWidth()/2,
                    bitmap.getWidth(),
                    bitmap.getWidth()
            );
        }

        dstRectForRender.set(50,20 ,500 ,360 );
        canvas2.drawBitmap(cropBmp, null, dstRectForRender, paint);

回答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));

[...]


来源:https://stackoverflow.com/questions/32905248/how-to-centercrop-an-image-programatically-by-maintaining-aspect-ratio-like-cent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!