Saturday, February 21, 2015

Create a Circular image view in android

Here is my article which is showing code for creating a circular image view in android using canvas. Using canvas it is easy to make circular image with some java code and there is no library required to implement this functionality.

Create a Circular image view in android



public class RoundedCorners extends ImageView {

private int RADIUS = 0;

public RoundedCorners(Context context) {
    super(context);
    init();
}

public RoundedCorners(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public RoundedCorners(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
}

@Override
public void onDraw(Canvas canvas) {


 Drawable maiDrawable = getDrawable();

   if (maiDrawable!=null && maiDrawable instanceof BitmapDrawable && RADIUS > 0)
{

       Paint paint = ((BitmapDrawable) maiDrawable).getPaint();
       final int color = 0xff000000;
       Rect bitmapBounds = maiDrawable.getBounds();
       final RectF rectF = new RectF(bitmapBounds);
       // Create an off-screen bitmap to the PorterDuff alpha blending to work right
       int saveCount = canvas.saveLayer(rectF, null,
               Canvas.MATRIX_SAVE_FLAG |
               Canvas.CLIP_SAVE_FLAG |
               Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
               Canvas.FULL_COLOR_LAYER_SAVE_FLAG |
               Canvas.CLIP_TO_LAYER_SAVE_FLAG);
       // Resize the rounded rect we'll clip by this view's current bounds
       // (super.onDraw() will do something similar with the drawable to draw)
   
              getImageMatrix().mapRect(rectF);

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

       Xfermode oldMode = paint.getXfermode();
       // This is the paint already associated with the BitmapDrawable that super draws
       paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
       super.onDraw(canvas);
       paint.setXfermode(oldMode);
       canvas.restoreToCount(saveCount);
   } else {
       super.onDraw(canvas);
   }
}

public void setRadius(int radius){
    this.RADIUS = radius;
}

private void init(){
    mRect = new RectF();
    mClip = new Path();
}
}


##Use this class in place of ImageView ,it will show rounded corner image (no need to make bitmap round..)
just add    imgview.setRadius();  //to set round value.

1 comments:

Don't lose faith when you see others receive answers to their prayers

An elephant and a dog became pregnant at same time. Three months down the line the dog gave birth to six puppies. Six months later the dog...

 

G-Expo Template by Ipietoon Cute Blog Design