Thursday 18 December 2014

Circular ImageView

Hello friends'

Today i will show, how to make a circular image through code.
Its pretty simple...
Lets see,

For this i am taking an ImageView and a sample image named default_image in drawable folder.

The Layout file code:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="100dp"
        android:layout_height="100dp" />

</LinearLayout>


The MainActivity java file code:

package in.blogspot.longjamcode;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.PorterDuff.Mode;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView image = (ImageView) findViewById(R.id.imageView);

//getting bitmap from drawable
Bitmap originalImageBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.default_image);

//resizing original bitmap, passed originalImageBitmap, the new bitmap's desired width, new bitmap's desired height, true if the source should be filtered.

Bitmap resized = Bitmap.createScaledBitmap(originalImageBitmap, 100, 100, false);
image.setImageBitmap(getRoundedBitmap(resized, 100));
}

//method to get rounded bitmap.
private Bitmap getRoundedBitmap(Bitmap bitmap, int pixels) {
Bitmap result = null;
try {
result = Bitmap.createBitmap(100,100, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
Rect rect = new Rect(0, 0, 200, 200);
paint.setAntiAlias(true);
canvas.drawCircle(50, 50, 50, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
} catch (NullPointerException e) {
} catch (OutOfMemoryError o) {
}
return result;
}
}

The sample output is




For full source code click here

No comments:

Post a Comment