Round images are a nice design element that add a touch of elegance to your application especially when used with feature images as a way to emphasize their content. In today’s tutorial we will show you how to create circular images on Android with Picasso image library.
Requirements
In this tutorial we assume you are using Picasso library for Android. If you are not, you should definitely give it a shot, because it helps to cache and load images very efficiently. Furthermore, it also allows you to apply custom transformations to images dynamically, such as the round transformation we will show you today. Really cool and powerful stuff!
In case you are just adding picasso to your project now, follow the instructions provided here. If you are using gradle, you simply add the library dependency and sync your project.
It does not matter whether you are using Java or Kotlin as your Android programming language. We will show you how to create round images in both languages.
Implementation
Next create a new class called CircleTransform.kt or CircleTransform.java. This will be where we define the transformation function. Based on the language you are using, implement the following functionality:
/** * Make a round image using picasso */ publicclassCircleTransformimplementsTransformation{ @Override public Bitmap transform(Bitmap source){ int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2; int y = (source.getHeight() - size) / 2;
Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size); if (squaredBitmap != source) { source.recycle(); }