Search code examples
androidimageimage-processingpicasso

Cropping image into circle


I want to crop a circle shape image from my original one. I'm using Picasso library for image displaying. Tried http://yasiradnan.com/circle-transformation-with-android-image-downloading-and-caching-library-picasso/ , but It's just tranforming full image into a circle one, so image became deformed. I don't want to transform image, I want just to crop image with circle shape.


Solution

  • To accomplish what you're trying to do, you could subclass ImageView and make it implement Picasso's Target interface. When the bitmap is loaded, just use a method that centercrops the bitmap into a square, and then shades the image into a circular shape. For example:

    public class ImageViewTarget extends ImageView implements Target {
    
        //constructors
    
    @Override
    public void onBitmapFailed(Drawable drawable) {
             //TODO
    }
    
    @Override
    public void onBitmapLoaded(Bitmap bitmap, LoadedFrom loadFrom) {
           bitmap = cropCircle(bitmap.isMutable() ? bitmap : bitmap.copy(Config.ARGB_8888, true));
               setImageBitmap(bitmap);
    }
    
    @Override
    public void onPrepareLoad(Drawable arg0) {
         //TODO
    }
    
    
    public Bitmap cropCricle(Bitmap bm){
    
        int width = bm.getWidth();
        int height = bm.getHeight();
    
        Bitmap cropped_bitmap;
    
        /* Crop the bitmap so it'll display well as a circle. */
        if (width > height) {
            cropped_bitmap = Bitmap.createBitmap(bm,
                    (width / 2) - (height / 2), 0, height, height);
        } else {
            cropped_bitmap = Bitmap.createBitmap(bm, 0, (height / 2)
                    - (width / 2), width, width);
        }
    
        BitmapShader shader = new BitmapShader(cropped_bitmap, TileMode.CLAMP, TileMode.CLAMP);
    
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setShader(shader);
    
        height = cropped_bitmap.getHeight();
        width = cropped_bitmap.getWidth();
    
        Bitmap mCanvasBitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
    
        Canvas canvas = new Canvas(mCanvasBitmap);
        canvas.drawCircle(width/2, height/2, width/2, paint);
    
        return mCanvasBitmap;
    }
    
    }
    

    There might be a better why to handle the cropCircle(Bitmap bitmap); method, but the above works as sometime to optimize/build off of.