圆形图片

imageview一般情况下为矩形,如果需要现实为圆角或者圆形还需要进行一番处理,这里自定义了一个imageview,可以修改角度来显示圆角图片

  1 import android.content.Context;
  2 import android.graphics.Bitmap;
  3 import android.graphics.Bitmap.Config;
  4 import android.graphics.Canvas;
  5 import android.graphics.Paint;
  6 import android.graphics.PorterDuff.Mode;
  7 import android.graphics.PorterDuffXfermode;
  8 import android.graphics.Rect;
  9 import android.graphics.RectF;
 10 import android.util.AttributeSet;
 11 import android.widget.ImageView;
 12 
 13 /**
 14 *  类名 CircleImageView
 15 *  @author 王洪贺<br/>
 16 *    圆形图像类
 17 *    创建日期 2014年7月14日
 18 */
 19 public class CircleImageView extends ImageView {
 20 
 21     /**默认显示的图像*/
 22     private int defaultImageRes = R.drawable.no_image;
 23     /**网络图像地址*/
 24     private String url;
 25     /**上下文*/
 26     private Context mContext;
 27 
 28     public CircleImageView(Context context) {
 29         super(context);
 30         init(context);
 31     }
 32 
 33     public CircleImageView(Context context, AttributeSet attrs, int defStyle) {
 34         super(context, attrs, defStyle);
 35         init(context);
 36     }
 37 
 38     public CircleImageView(Context context, AttributeSet attrs) {
 39         super(context, attrs);
 40         init(context);
 41     }
 42 
 43     public void init(Context context) {
 44         this.mContext = context;
 45     }
 46 
 47     public void setDefault(int resId) {
 48         defaultImageRes = resId;
 49     }
 50 
 51     public void setUrl(String imageUrl) {
 52         url = imageUrl;
 53     }
 54 
 55     @Override
 56     public void setImageBitmap(Bitmap bm) {
 57         if (bm != null) {
 58             bm = toRoundBitmap(bm);
 59             // bitmap = bm;
 60         }
 61         super.setImageBitmap(bm);
 62     }
 63 
 64     @Override
 65     public void setImageResource(int resId) {
 66         super.setImageResource(resId);
 67 
 68     }
 69 
 70     /**
 71      * 转换图片成圆形
 72      * 
 73      * @param bitmap
 74      *            传入Bitmap对象
 75      * @return
 76      */
 77     public Bitmap toRoundBitmap(Bitmap bitmap) {
 78 
 79         Bitmap output = Bitmap
 80                 .createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
 81         Canvas canvas = new Canvas(output);
 82 
 83         final int color = 0xff424242;
 84         final Paint paint = new Paint();
 85         final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
 86         final RectF rectF = new RectF(rect);
 87         final float roundPx = 90;
 88 
 89         paint.setAntiAlias(true);
 90         canvas.drawARGB(0, 0, 0, 0);
 91         paint.setColor(color);
 92         canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
 93 
 94         paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
 95         canvas.drawBitmap(bitmap, rect, rect, paint);
 96 
 97         return output;
 98     }
 99 
100 }
原文地址:https://www.cnblogs.com/dongweiq/p/3906618.html