Crop square image to circle - Programmatically

前端 未结 7 1428
余生分开走
余生分开走 2020-12-01 01:14

i was searching for past one day and i was not successful .

i get the image from API , and i download it to a bitmap file using the following code .

         


        
7条回答
  •  死守一世寂寞
    2020-12-01 01:28

    I tried the solutions above but none worked well for me. This is because my phone camera don't take square image but just rectangle images. So, I make some changes in the @actsai solution to always take the minor dimension and then crop the image in a circle:

    public static Bitmap getBitmapClip(Bitmap bitmap) {
        int maxLenth = bitmap.getWidth() <= bitmap.getHeight() ? bitmap.getWidth() : bitmap.getHeight();
        Bitmap output = Bitmap.createBitmap(maxLenth,
                maxLenth, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
    
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, maxLenth, maxLenth);
    
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        canvas.drawCircle(maxLenth / 2, maxLenth / 2,
                maxLenth / 2, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }
    

    I used the following scale property to fill my ImageView with the new bitmap:

    
    

提交回复
热议问题