0

Android imageview with rounded corners programmatically

Dynamically create rounded corners image using coding, image source is drawable-hdpi folder.

Displaying rounded corners  image inside ImageView is very easy using Bitmap classes. Because with the help of Bitmap library app developer can firstly convert normal image into Bitmap then modify its corners using setCornerRadius() method. So here is the complete step by step tutorial for Android imageview with rounded corners programmatically.

android-project-download-code-button

Note: Copy image inside drawable-hdpi folder.

drawable hdpi folder

Download sample image from below and put it inside drawable-hdpi folder.

sample_round-image

Android imageview with rounded corners programmatically.

Code for MainActivity.java file.

 package com.imageviewroundedcornersxml_android_examples.com;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.widget.ImageView;

public class MainActivity extends Activity {
 
 ImageView NormalImageView;
 Bitmap ImageBit;
 float ImageRadius = 40.0f;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 NormalImageView = (ImageView)findViewById(R.id.imageView1);
 
 ImageBit = BitmapFactory.decodeResource(getResources(), R.drawable.sample_round_image);

 NormalImageView.setImageBitmap(ImageBit);
 
 RoundedBitmapDrawable RBD = RoundedBitmapDrawableFactory.create(getResources(),ImageBit);

 RBD.setCornerRadius(ImageRadius);
 
 RBD.setAntiAlias(true);
 
 NormalImageView.setImageDrawable(RBD);
 
 }
 }

Code for activity_main.xml layout file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.imageviewroundedcornersxml_android_examples.com.MainActivity" >

 <ImageView
 android:id="@+id/imageView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 />

</RelativeLayout>

Screenshot :

Android imageview with rounded corners programmatically

Click here to download Android imageview with rounded corners programmatically project.

Leave a Reply

Your email address will not be published. Required fields are marked *