Imageview customization (circular image view)

In android designing, we'll come across ImageView. An ImageView displays an arbitrary image, such as an icon. The ImageView class can load images from various sources (such as resources or content providers), takes care of computing its measurement from the image so that it can be used in any layout manager, and provides various display options such as scaling and tinting.Sometimes during designing, we may have to get the image in different shapes like oval, rectangle, circular etc.., for that purpose, it is recommended to customise it through bitmaps(BitMap in android) instead of reshaping the image manually.

Simple steps to customize the ImageView:

1.Convert the ImageView into a bitmap object.

ImageView img;
img.setDrawingCacheEnabled(true);
Bitmap scaledBitmap = img.getDrawingCache();

2.Create a target bitmap with the required width and height.

Bitmap targetBitmap = Bitmap.createBitmap(targetWidth,targetHeight,Bitmap.Config.ARGB_8888);

3.Create a canvas(Canvas to host the draw calls (writing into the bitmap)) for that taget bitmap.

Canvas canvas = new Canvas(targetBitmap);

3.draw a circle on that canvas with the required radius.

canvas.drawCircle(targetWidth / 2+0.7f, targetHeight / 2+0.7f,targetWidth / 2+0.1f, paint);
Note: if you want to style or draw geometries to the canvas use Paint object otherwise give 'null'

4.Draw the specified bitmap, scaling/translating automatically to fill the destination rectangle on the canvas which gives the required circular bitmap.

canvas.drawBitmap(sourceBitmap,new Rect(0, 0, sourceBitmap.getWidth(),sourceBitmap.getHeight()),new Rect(0, 0, targetWidth,targetHeight), paint);

Note: if you want to style or draw geometries to the canvas use Paint object otherwise give 'null'

5.Create a Paint object(The Paint class holds the style and color information about how to draw geometries, text and bitmaps.) to give the border for the imageview if required.create the canvas for the btimap and draw the circle on the canvas with paint object which gives the bitmap image with circular boarder.

Paint paint = new Paint();
paint.setStyle(Style.STROKE);
paint.setColor(Color.parseColor("#D1D0CE"));
paint.setStrokeWidth(5);
Canvas c = new Canvas(targetBitmap);
c.drawCircle(int w, int h, radius, paint);

6.Load the imageview with the final target bitmap that is formed after drawing the bitmap with on the canvas.

imageView.setImageBitmap(targetBitmap);

Posted On 23 January 2014 By MicroPyramid


Need any Help in your Project?Let's Talk

Latest Comments
open source packages

Subscribe To our news letter

Subscribe and Stay Updated about our Webinars, news and articles on Django, Python, Machine Learning, Amazon Web Services, DevOps, Salesforce, ReactJS, AngularJS, React Native.
* We don't provide your email contact details to any third parties