Monday, 8 June 2015

Create a circle bitmap in Android

Very often in today's modern applications, we can see a profile picture in a circle shape.
Today, we' ll create a method that takes square bitmap and later it returns circle shaped bitmap. 
What we'll do first is add some random image in our drawable folder. Let's call it simple_image.jpg. 
Next we'll create the activity_main.xml layout that will display the modified image and will be used in MainActivity. 
The activity_main.xml layout is very simple, it contains only ImageView.

ctivity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:background="@android:color/darker_gray"
    tools:context="com.example.circlebitmaptest.MainActivity" >
    
    <ImageView 
        android:id="@+id/image"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:scaleType="fitXY"/>

</LinearLayout>

Now let's create the method that will create a circle shaped bitmap. 
As you can see the method receives a bitmap object as a parameter.We'll send that bitmap later from the onCreate method.

private Bitmap getCircleBitmap(Bitmap bitmap) {
 final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
  bitmap.getHeight(), Bitmap.Config.ARGB_8888);
 final Canvas canvas = new Canvas(output);

 final int color = Color.RED;
 final Paint paint = new Paint();
 final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
 final RectF rectF = new RectF(rect);

 paint.setAntiAlias(true);
 canvas.drawARGB(0, 0, 0, 0);
 paint.setColor(color);
 canvas.drawOval(rectF, paint);

 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
 canvas.drawBitmap(bitmap, rect, rect, paint);

 bitmap.recycle();

 return output;
}

The last thing we need to do is to decode the image resource from our drawable folder into a bitmap object, find the ImageView that will be used to display the image, and add the rounded bitmap to the ImageView.We'll do all of this in the onCreate() method.

@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 // create bitmap from resource
 Bitmap bm = BitmapFactory.decodeResource(getResources(),
  R.drawable.simple_image);

 // set circle bitmap
 ImageView mImage = (ImageView) findViewById(R.id.image);
 mImage.setImageBitmap(getCircleBitmap(bm));

}

    No comments:

    Post a Comment