在Android中裁剪图像为圆圈

Ale*_*lim 8 android crop android-image

有谁知道如何将图像\位图裁剪成圆圈?我找不到任何解决方案,抱歉..

Aj *_* 27 6

为了使ImageView具有圆角,请将图像转换为位图,然后尝试以下代码:

     private Bitmap getRoundedCroppedBitmap(Bitmap bitmap) {
        int widthLight = bitmap.getWidth();
        int heightLight = bitmap.getHeight();

        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),Config.ARGB_8888);

        Canvas canvas = new Canvas(output);
        Paint paintColor = new Paint();
        paintColor.setFlags(Paint.ANTI_ALIAS_FLAG);

        RectF rectF = new RectF(new Rect(0, 0, widthLight, heightLight));

        canvas.drawRoundRect(rectF, widthLight / 2 ,heightLight / 2,paintColor);

        Paint paintImage = new Paint();
        paintImage.setXfermode(new PorterDuffXfermode(Mode.SRC_ATOP));
        canvas.drawBitmap(bitmap, 0, 0, paintImage);

        return output;
    }
Run Code Online (Sandbox Code Playgroud)


Fra*_*ndo 0

尝试使用下面的代码:

public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
  // TODO Auto-generated method stub
  int targetWidth = 50;
  int targetHeight = 50;
  Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, 
                            targetHeight,Bitmap.Config.ARGB_8888);

                Canvas canvas = new Canvas(targetBitmap);
  Path path = new Path();
  path.addCircle(((float) targetWidth - 1) / 2,
  ((float) targetHeight - 1) / 2,
  (Math.min(((float) targetWidth), 
                ((float) targetHeight)) / 2),
          Path.Direction.CCW);

                canvas.clipPath(path);
  Bitmap sourceBitmap = scaleBitmapImage;
  canvas.drawBitmap(sourceBitmap, 
                                new Rect(0, 0, sourceBitmap.getWidth(),
    sourceBitmap.getHeight()), 
                                new Rect(0, 0, targetWidth,
    targetHeight), null);
  return targetBitmap;
 }
Run Code Online (Sandbox Code Playgroud)