Langsung ke konten utama

Circle Image View using Glide and Picasso in Android


Hello guys, In this tutorial we will learn how to create Circular Image View in Android without using any additional Libraries such as CircleImageView.
// This Library is very Popular and Widely used for Circle Image View
compile 'de.hdodenhof:circleimageview:2.1.0'
Nowadays, Every Android Developers uses Glide or Picasso Image HTTP Libraries to Image in Image Views. If we uses any additional Libraries to get Circle Shaped Image View may lead to increase the size of an APK. To avoid this, Glide and Picasso provides solution to create Circle Image View.

First, we will see how create circle image using Picasso.

Circle Transformation using Picasso

Download Picasso by Gradle in Android
// This Library is created by Square.Inc
compile 'com.squareup.picasso:picasso:2.5.2'
The following snippet is used to load image into ImageView using Picasso
Picasso.with(getApplicationContext()).load("http://i.imgur.com/DvpvklR.png")
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into((ImageView) findViewById(R.id.picassoImageView));
To create circle image, create a class named as PicassoCircleTransformation and paste the following code
public class PicassoCircleTransformation implements Transformation {

@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();
}

Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());

Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
BitmapShader shader = new BitmapShader(squaredBitmap,
BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
paint.setShader(shader);
paint.setAntiAlias(true);

float r = size / 2f;
canvas.drawCircle(r, r, r, paint);

squaredBitmap.recycle();
return bitmap;
}

@Override
public String key() {
return "circle";
}
}
Then load the transformation as like the following
Picasso.with(getApplicationContext()).load("http://i.imgur.com/DvpvklR.png")
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.transform(new PicassoCircleTransformation())
.into((ImageView) findViewById(R.id.picassoImageView));
Now we will see, how to create circle transformation using Glide

Circle Transformation using Glide

Download Glide by Gradle in Android
// This Library is created by Bumptech
compile 'com.github.bumptech.glide:glide:3.7.0'
The following snippet is used to load image into ImageView using Glide
Glide.with(getApplicationContext()).load("http://i.imgur.com/DvpvklR.png")
.thumbnail(0.5f)
.crossFade()
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into((ImageView) findViewById(R.id.glideImageView));
To create circle image, create a class named as GlideCircleTransformation and paste the following code
public class GlideCircleTransformation implements Transformation {

private BitmapPool mBitmapPool;

public GlideCircleTransformation(Context context) {
this(Glide.get(context).getBitmapPool());
}

public GlideCircleTransformation(BitmapPool pool) {
this.mBitmapPool = pool;
}

@Override
public Resource transform(Resource resource, int outWidth, int outHeight) {
Bitmap source = resource.get();
int size = Math.min(source.getWidth(), source.getHeight());

int width = (source.getWidth() - size) / 2;
int height = (source.getHeight() - size) / 2;

Bitmap bitmap = mBitmapPool.get(size, size, Bitmap.Config.ARGB_8888);
if (bitmap == null) {
bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
}

Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
BitmapShader shader =
new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
if (width != 0 || height != 0) {
// source isn't square, move viewport to center
Matrix matrix = new Matrix();
matrix.setTranslate(-width, -height);
shader.setLocalMatrix(matrix);
}
paint.setShader(shader);
paint.setAntiAlias(true);

float r = size / 2f;
canvas.drawCircle(r, r, r, paint);

return BitmapResource.obtain(bitmap, mBitmapPool);
}

@Override public String getId() {
return "GlideCircleTransformation()";
}
}
Then load the transformation in Glide as like the following
Glide.with(getApplicationContext()).load("http://i.imgur.com/DvpvklR.png")
.thumbnail(0.5f)
.crossFade()
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.bitmapTransform(new GlideCircleTransformation(getApplicationContext()))
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into((ImageView) findViewById(R.id.glideImageView));

Download Code:

You can download the full source from the following Github link. If you Like this tutorial, Please star it in Github.
    
Download From Github

I found these snippets from Wasabeef Transformations Libraries for Glide and Picasso.
Post your doubts and comments in the comments section.  

Komentar

Postingan populer dari blog ini

FlatBuffers Android Tutorial

FlatBuffers is an efficient cross platform serialization library for C++, Java, C#, Go, Python and JavaScript. It was originally created at Google for game development and other performance-critical applications. FlatBuffers is Open Source (Apache license V2) and available on GitHub . It's currently used by:   Cocos2d-x , the open source mobile game engine and used to serialize the game data. Facebook uses it for client-server communication in the Android app (see the article) . Fun Propulsion Labs at Google in most of libraries and games. Solution overview  The schema will be defind in JSON format, then it will be converted to FlatBuffer format outside the application The Java classes of the Data model will be generated manually using flatc (FlatBuffer compiler) Step 1: Build FlatBuffers Download the source code in Google’s flatbuffers repository .  The build process is described on Google's documentation FlatBuffers Building .  On MacOS for example: Open the xcode proje

QR-Code Generator - Library

In this Post, I introduce my new Gradle Library. This Library is used to Generate QR Code Automatically for our specified input. How to Import the Library: Gradle: compile 'androidmads.library.qrgenearator:QRGenearator:1.0.0' Permission: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> How to use this Library: After importing this library, use the following lines to use this library. The following lines are used to generated the QR Code // Initializing the QR Encoder with your value to be encoded, type you required and Dimension QRGEncoder qrgEncoder = new QRGEncoder(inputValue, null, QRGContents.Type.TEXT, smallerDimension); try { // Getting QR-Code as Bitmap bitmap = qrgEncoder.encodeAsBitmap(); // Setting Bitmap to ImageView qrImage.setImageBitmap(bitmap); } catch (WriterException e) { Log.v(TAG, e.toString()); } Save QR Code as Image // Save with location, value, bitmap returned and type of Image(JPG/PNG). QRGSaver.save(s

Download file using Okio in Android

Okio is a library that complements java.io and java.nio to make it much easier to access, store, and process your data. Simply Okio is a modern I/O API for Java.  In this post, we will see how to download image or any file using Okio. Okio is component for OkHttp Coding Part Create a new project in Android Studio. Add following dependencies to your  app-level  build.gradle  file. compile 'com.squareup.okhttp3:okhttp:3.6.0' Don't forget to add the following permission in your AndroidManifest.xml <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> Implementation Paste the following code in your Activity and Here, I have kept as MainActivity.java public void downloadImg(View view) { try { Request request = new Request.Builder() .url(imageLink) .build(); new OkHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFail