TrinityTuts Tips

Create round image by code android

In this i tip i am going to sharing some useful code to create round  or circle image in android and set on imageview or image button.

Convert Image to Bitmap and Crop image if you want to set image in specific view

public Bitmap localImageToBitmap(int source, int THUMBNAIL_SIZE) {
        int size = THUMBNAIL_SIZE;
        Bitmap imageBitmap = BitmapFactory.decodeResource(activity.getResources(), source);
        imageBitmap = Bitmap.createScaledBitmap(imageBitmap, size, size, false);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        return imageBitmap;
    }

Now create round image and return image in bitmap

public Bitmap transform(Bitmap source, int radius, int margin) {
        final Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP,
                Shader.TileMode.CLAMP));

        Bitmap output = Bitmap.createBitmap(source.getWidth(),
                source.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        canvas.drawRoundRect(new RectF(margin, margin, source.getWidth()
                - margin, source.getHeight() - margin), radius, radius, paint);

        if (source != output) {
            source.recycle();
        }
        return output;
    }

Now you can call this method on ImageView or in ImageButton

ImageButton songProfile = (ImageButton) findViewById(R.id.songProfile);
        songProfile.setImageBitmap(utils.transform(utils.getRoundedCornerImage(utils.localImageToBitmap(R.drawable.song, 120)), 100, 0));

Happy coding 🙂