圆形图片帮助类

废话不多说,直接上代码

/**
* 圆形ImageView
*
* @author skg
*
*/ public class CircleImageView extends ImageView {

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

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

   private final RectF roundRect = new RectF();
   private float rect_adius = 8;
   private final Paint maskPaint = new Paint();
   private final Paint zonePaint = new Paint();

   private void init() {
       maskPaint.setAntiAlias(true);
       maskPaint.setFilterBitmap(true);
       maskPaint.setDither(true);
       maskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
       zonePaint.setAntiAlias(true);
       zonePaint.setFilterBitmap(true);
       zonePaint.setDither(true);
       zonePaint.setColor(Color.WHITE);
                float density = getResources().getDisplayMetrics().density;
       rect_adius = rect_adius * density;
   }

   public void setRectAdius(float adius) {
       rect_adius = adius;
       invalidate();
   }

   @Override
   protected void onLayout(boolean changed, int left, int top, int right,
           int bottom) {
       super.onLayout(changed, left, top, right, bottom);
       int w = getWidth();
       rect_adius = getWidth();
       int h = getHeight();
       roundRect.set(0, 0, w, h);
   }

   @Override
   public void draw(Canvas canvas) {
       canvas.saveLayer(roundRect, zonePaint, Canvas.ALL_SAVE_FLAG);
       canvas.drawRoundRect(roundRect, rect_adius, rect_adius, zonePaint);
       canvas.saveLayer(roundRect, maskPaint, Canvas.ALL_SAVE_FLAG);
       super.draw(canvas);
       canvas.restore();
   }
}

使用方法:
在xml文件中声明即可,在Activity中的使用方法和普通的控件一致

<你的完整的包名.CircleImageView
                    android:id="@+id/my_icon_iv"
                    android:layout_width="70dp"
                    android:layout_height="70dp"
                    android:src="@drawable/user_icon">



你可能感兴趣的:(圆形图片帮助类)