Friday, December 27, 2013

Create rounded Imageview

This post is to create rounded imageview in android application.
Use this below method for creare rounded shape image view in android.

public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
// TODO Auto-generated method stub
int targetWidth = 50;
int targetHeight = 50;
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight,
Bitmap.Config.ARGB_8888);

Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addCircle(((float) targetWidth - 1) / 2,
((float) targetHeight - 1) / 2,
(Math.min(((float) targetWidth), ((float) targetHeight)) / 2),
Path.Direction.CCW);

canvas.clipPath(path);
Bitmap sourceBitmap = scaleBitmapImage;
canvas.drawBitmap(sourceBitmap, new Rect(0, 0, sourceBitmap.getWidth(),
sourceBitmap.getHeight()), new Rect(0, 0, targetWidth,
targetHeight), null);
return targetBitmap;
}


Using this methods you can create your imageview rounded in application.

int targetWidth = 50;
int targetHeight = 50;

Using above variable you can set your image view size.

How to set rounded shape imageview in activity
In your activity use this method like this.


public class MainActivity extends Activity {

private ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView)findViewById(R.id.img);
Bitmap bitmap = getRoundedShape(BitmapFactory.decodeResource(
MainActivity.this.getResources(), R.drawable.ic_launcher));

img.setImageBitmap(bitmap);
}

public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
int targetWidth = 50;
int targetHeight = 50;
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight,
Bitmap.Config.ARGB_8888);

Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addCircle(((float) targetWidth - 1) / 2,
((float) targetHeight - 1) / 2,
(Math.min(((float) targetWidth), ((float) targetHeight)) / 2),
Path.Direction.CCW);

canvas.clipPath(path);
Bitmap sourceBitmap = scaleBitmapImage;
canvas.drawBitmap(sourceBitmap, new Rect(0, 0, sourceBitmap.getWidth(),
sourceBitmap.getHeight()), new Rect(0, 0, targetWidth,
targetHeight), null);
return targetBitmap;
}

}

Output of ImageView:


No comments:

Post a Comment