在Android開發中我們常常用到圓形的頭像,如果每次加載之后再進行圓形裁剪特別麻煩。所以在這里寫一個自定義圓形ImageView,直接去加載網絡圖片,這樣的話就特別的方便。
先上效果圖

主要的方法
1.讓自定義 CircleImageView 繼承ImageView
/*** 自定義圓形頭像* Created by Dylan on 2015/11/26 0026.*/public class CircleImageView extends ImageView {}2.在構造方法中獲取在xml中設置的值
public CircleImageView(Context context) {super(context);}public CircleImageView(Context context, AttributeSet attrs) {this(context, attrs, 0);}public CircleImageView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);super.setScaleType(SCALE_TYPE);/*** 獲取在xml中聲明的屬性*/TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView, defStyle, 0);//獲取xml中的屬性mBorderWidth = a.getDimensionPixelSize(R.styleable.CircleImageView_border_width, DEFAULT_BORDER_WIDTH);mBorderColor = a.getColor(R.styleable.CircleImageView_border_color, DEFAULT_BORDER_COLOR);a.recycle();mReady = true;if (mSetupPending) {setup();mSetupPending = false;}}3.初始化各種參數設置
/*** 畫圓形圖的初始化工作*/private void setup() {if (!mReady) {mSetupPending = true;return;}if (mBitmap == null) {return;}/***調用這個方法來產生一個畫有一個位圖的渲染器(Shader)。bitmap 在渲染器內使用的位圖tileX The tiling mode for x to draw the bitmap in. 在位圖上X方向花磚模式tileY The tiling mode for y to draw the bitmap in. 在位圖上Y方向花磚模式TileMode:(一共有三種)CLAMP :如果渲染器超出原始邊界范圍,會復制范圍內邊緣染色。REPEAT :橫向和縱向的重復渲染器圖片,平鋪。MIRROR :橫向和縱向的重復渲染器圖片,這個和REPEAT 重復方式不一樣,他是以鏡像方式平鋪。*/mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);/*** 設置畫圓形的畫筆*/mBitmapPaint.setAntiAlias(true);//設置抗鋸齒mBitmapPaint.setShader(mBitmapShader);//繪制圖形時的圖形變換mBorderPaint.setStyle(Paint.Style.STROKE);mBorderPaint.setAntiAlias(true);mBorderPaint.setColor(mBorderColor);mBorderPaint.setStrokeWidth(mBorderWidth);mBitmapHeight = mBitmap.getHeight();mBitmapWidth = mBitmap.getWidth();/*** 設置邊框矩形的坐標*/mBorderRect.set(0, 0, getWidth(), getHeight());/*** 設置邊框圓形的半徑為圖片的寬度和高度的一半的最大值*/mBorderRadius = Math.max((mBorderRect.height() - mBorderWidth) / 2, (mBorderRect.width() - mBorderWidth) / 2);/*** 設置圖片矩形的坐標*/mDrawableRect.set(mBorderWidth, mBorderWidth, mBorderRect.width() - mBorderWidth, mBorderRect.height() - mBorderWidth);/*** 設置圖片圓形的半徑為圖片的寬度和高度的一半的最大值*/mDrawableRadius = Math.max(mDrawableRect.height() / 2, mDrawableRect.width() / 2);updateShaderMatrix();/*** 調用onDraw()方法進行繪畫*/invalidate();}/*** 更新位圖渲染*/private void updateShaderMatrix() {float scale;float dx = 0;float dy = 0;/*** 重置*/mShaderMatrix.set(null);/***計算縮放比,因為如果圖片的尺寸超過屏幕,那么就會自動匹配到屏幕的尺寸去顯示。* 確定移動的xy坐標**/if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width() * mBitmapHeight) {scale = mDrawableRect.width() / (float) mBitmapWidth;dy = (mDrawableRect.height() - mBitmapHeight * scale) * 0.5f;} else {scale = mDrawableRect.height() / (float) mBitmapHeight;dx = (mDrawableRect.width() - mBitmapWidth * scale) * 0.5f;}mShaderMatrix.setScale(scale, scale);mShaderMatrix.postTranslate((int) (dx + 0.5f) + mBorderWidth, (int) (dy + 0.5f) + mBorderWidth);/*** 設置shader的本地矩陣*/mBitmapShader.setLocalMatrix(mShaderMatrix);}4.畫圓
@Overrideprotected void onDraw(Canvas canvas) {if (getDrawable() == null) {return;}/*** 畫圓形圖片*/canvas.drawCircle(getWidth() / 2, getHeight() / 2, mDrawableRadius, mBitmapPaint);/*** 畫圓形邊框*/canvas.drawCircle(getWidth() / 2, getHeight() / 2, mBorderRadius, mBorderPaint);}完整代碼,有完整的注釋
1.CircleImageView 主類
import android.content.Context;import android.content.res.TypedArray;import android.graphics.Bitmap;import android.graphics.BitmapShader;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Matrix;import android.graphics.Paint;import android.graphics.RectF;import android.graphics.Shader;import android.graphics.drawable.BitmapDrawable;import android.graphics.drawable.ColorDrawable;import android.graphics.drawable.Drawable;import android.util.AttributeSet;import android.widget.ImageView;import com.kejiang.yuandl.R;import com.kejiang.yuandl.utils.ImageSizeUtil;/*** 自定義圓形頭像* Created by Dylan on 2015/11/26 0026.*/public class CircleImageView extends ImageView {/*** 圓形頭像默認,CENTER_CROP!=系統默認的CENTER_CROP;* 將圖片等比例縮放,讓圖像的長邊邊與ImageView的邊長度相同,短邊不夠的留空白,縮放后截取圓形部分進行顯示。*/private static final ScaleType SCALE_TYPE = ScaleType.CENTER_CROP;/*** 圖片的壓縮質量* ALPHA_8就是Alpha由8位組成,------ALPHA_8 代表8位Alpha位圖* ARGB_4444就是由4個4位組成即16位,------ARGB_4444 代表16位ARGB位圖* ARGB_8888就是由4個8位組成即32位,------ARGB_8888 代表32位ARGB位圖* RGB_565就是R為5位,G為6位,B為5位共16位,------ARGB_565 代表8位RGB位圖*/private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888;/*** 默認ColorDrawable的寬和高*/private static final int COLORDRAWABLE_DIMENSION = 1;/*** 默認邊框寬度*/private static final int DEFAULT_BORDER_WIDTH = 0;/*** 默認邊框顏色*/private static final int DEFAULT_BORDER_COLOR = Color.BLACK;/*** 畫圖片的矩形*/private final RectF mDrawableRect = new RectF();/*** 畫邊框的矩形*/private final RectF mBorderRect = new RectF();/*** 對圖片進行縮放和移動的矩陣*/private final Matrix mShaderMatrix = new Matrix();/*** 畫圖片的畫筆*/private final Paint mBitmapPaint = new Paint();/*** 畫邊框的畫筆*/private final Paint mBorderPaint = new Paint();/*** 默認邊框顏色*/private int mBorderColor = DEFAULT_BORDER_COLOR;/*** 默認邊框寬度*/private int mBorderWidth = DEFAULT_BORDER_WIDTH;private Bitmap mBitmap;/*** 產生一個畫有一個位圖的渲染器(Shader)*/private BitmapShader mBitmapShader;/*** 圖片的實際寬度*/private int mBitmapWidth;/*** 圖片實際高度*/private int mBitmapHeight;/*** 圖片半徑*/private float mDrawableRadius;/*** 邊框半徑*/private float mBorderRadius;/*** 是否初始化準備好*/private boolean mReady;/*** 內邊距*/private boolean mSetupPending;public CircleImageView(Context context) {super(context);}public CircleImageView(Context context, AttributeSet attrs) {this(context, attrs, 0);}public CircleImageView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);super.setScaleType(SCALE_TYPE);/*** 獲取在xml中聲明的屬性*/TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView, defStyle, 0);//獲取xml中的屬性mBorderWidth = a.getDimensionPixelSize(R.styleable.CircleImageView_border_width, DEFAULT_BORDER_WIDTH);mBorderColor = a.getColor(R.styleable.CircleImageView_border_color, DEFAULT_BORDER_COLOR);a.recycle();mReady = true;if (mSetupPending) {setup();mSetupPending = false;}}@Overridepublic ScaleType getScaleType() {return SCALE_TYPE;}@Overrideprotected void onDraw(Canvas canvas) {if (getDrawable() == null) {return;}/*** 畫圓形圖片*/canvas.drawCircle(getWidth() / 2, getHeight() / 2, mDrawableRadius, mBitmapPaint);/*** 畫圓形邊框*/canvas.drawCircle(getWidth() / 2, getHeight() / 2, mBorderRadius, mBorderPaint);}@Overrideprotected void onSizeChanged(int w, int h, int oldw, int oldh) {super.onSizeChanged(w, h, oldw, oldh);setup();}/*** 獲取邊框顏色** @return*/public int getBorderColor() {return mBorderColor;}/*** 設置邊框顏色** @param borderColor*/public void setBorderColor(int borderColor) {if (borderColor == mBorderColor) {return;}mBorderColor = borderColor;mBorderPaint.setColor(mBorderColor);invalidate();}/*** 獲取邊框寬度** @return*/public int getBorderWidth() {return mBorderWidth;}/*** 設置邊框寬度** @param borderWidth*/public void setBorderWidth(int borderWidth) {if (borderWidth == mBorderWidth) {return;}mBorderWidth = borderWidth;setup();}/*** 設置資源圖片** @param bm*/@Overridepublic void setImageBitmap(Bitmap bm) {super.setImageBitmap(bm);mBitmap = bm;setup();}/*** 設置資源圖片** @param drawable*/@Overridepublic void setImageDrawable(Drawable drawable) {super.setImageDrawable(drawable);mBitmap = getBitmapFromDrawable(drawable);setup();}/*** 設置資源id** @param resId*/@Overridepublic void setImageResource(int resId) {super.setImageResource(resId);mBitmap = getBitmapFromDrawable(getDrawable());setup();}/*** 獲取資源圖片** @param drawable* @return*/private Bitmap getBitmapFromDrawable(Drawable drawable) {if (drawable == null) {return null;}if (drawable instanceof BitmapDrawable) {return ((BitmapDrawable) drawable).getBitmap();}try {Bitmap bitmap;if (drawable instanceof ColorDrawable) {bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG);} else {ImageSizeUtil.ImageSize imageSize = ImageSizeUtil.getImageViewSize(this);bitmap = Bitmap.createBitmap(imageSize.width,imageSize.height, BITMAP_CONFIG);}Canvas canvas = new Canvas(bitmap);drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());drawable.draw(canvas);return bitmap;} catch (OutOfMemoryError e) {return null;}}/*** 畫圓形圖的方法*/private void setup() {if (!mReady) {mSetupPending = true;return;}if (mBitmap == null) {return;}/***調用這個方法來產生一個畫有一個位圖的渲染器(Shader)。bitmap 在渲染器內使用的位圖tileX The tiling mode for x to draw the bitmap in. 在位圖上X方向花磚模式tileY The tiling mode for y to draw the bitmap in. 在位圖上Y方向花磚模式TileMode:(一共有三種)CLAMP :如果渲染器超出原始邊界范圍,會復制范圍內邊緣染色。REPEAT :橫向和縱向的重復渲染器圖片,平鋪。MIRROR :橫向和縱向的重復渲染器圖片,這個和REPEAT 重復方式不一樣,他是以鏡像方式平鋪。*/mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);/*** 設置畫圓形的畫筆*/mBitmapPaint.setAntiAlias(true);//設置抗鋸齒mBitmapPaint.setShader(mBitmapShader);//繪制圖形時的圖形變換mBorderPaint.setStyle(Paint.Style.STROKE);mBorderPaint.setAntiAlias(true);mBorderPaint.setColor(mBorderColor);mBorderPaint.setStrokeWidth(mBorderWidth);mBitmapHeight = mBitmap.getHeight();mBitmapWidth = mBitmap.getWidth();/*** 設置邊框矩形的坐標*/mBorderRect.set(0, 0, getWidth(), getHeight());/*** 設置邊框圓形的半徑為圖片的寬度和高度的一半的最大值*/mBorderRadius = Math.max((mBorderRect.height() - mBorderWidth) / 2, (mBorderRect.width() - mBorderWidth) / 2);/*** 設置圖片矩形的坐標*/mDrawableRect.set(mBorderWidth, mBorderWidth, mBorderRect.width() - mBorderWidth, mBorderRect.height() - mBorderWidth);/*** 設置圖片圓形的半徑為圖片的寬度和高度的一半的最大值*/mDrawableRadius = Math.max(mDrawableRect.height() / 2, mDrawableRect.width() / 2);updateShaderMatrix();/*** 調用onDraw()方法進行繪畫*/invalidate();}/*** 更新位圖渲染*/private void updateShaderMatrix() {float scale;float dx = 0;float dy = 0;/*** 重置*/mShaderMatrix.set(null);/***計算縮放比,因為如果圖片的尺寸超過屏幕,那么就會自動匹配到屏幕的尺寸去顯示。* 確定移動的xy坐標**/if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width() * mBitmapHeight) {scale = mDrawableRect.width() / (float) mBitmapWidth;dy = (mDrawableRect.height() - mBitmapHeight * scale) * 0.5f;} else {scale = mDrawableRect.height() / (float) mBitmapHeight;dx = (mDrawableRect.width() - mBitmapWidth * scale) * 0.5f;}mShaderMatrix.setScale(scale, scale);mShaderMatrix.postTranslate((int) (dx + 0.5f) + mBorderWidth, (int) (dy + 0.5f) + mBorderWidth);/*** 設置shader的本地矩陣*/mBitmapShader.setLocalMatrix(mShaderMatrix);}}2.里面所使用到的ImageSizeUtil
public class ImageSizeUtil{/*** 根據ImageView獲適當的壓縮的寬和高* * @param imageView* @return*/public static ImageSize getImageViewSize(ImageView imageView){ImageSize imageSize = new ImageSize();DisplayMetrics displayMetrics = imageView.getContext().getResources().getDisplayMetrics();LayoutParams lp = imageView.getLayoutParams();int width = imageView.getWidth();// 獲取imageview的實際寬度if (width <= 0){if(lp!=null){width = lp.width;// 獲取imageview在layout中聲明的寬度}}if (width <= 0){//width = imageView.getMaxWidth();// 檢查最大值width = getImageViewFieldValue(imageView, "mMaxWidth");}if (width <= 0){width = displayMetrics.widthPixels;}int height = imageView.getHeight();// 獲取imageview的實際高度if (height <= 0){if(lp!=null){height = lp.height;// 獲取imageview在layout中聲明的寬度}}if (height <= 0){height = getImageViewFieldValue(imageView, "mMaxHeight");// 檢查最大值}if (height <= 0){height = displayMetrics.heightPixels;}imageSize.width = width;imageSize.height = height;return imageSize;}public static class ImageSize{public int width;public int height;}}用法
布局文件
<com.bulemobi.yuandl.view.CircleImageViewandroid:id="@+id/ci"android:layout_width="180dp"android:layout_height="180dp"android:scaleType="centerCrop"android:layout_gravity="center_horizontal"app:border_width="1dp"app:border_color="#FF0000"/>
Activity中的代碼,用xutils3加載圖片
CircleImageView circleImageView= (CircleImageView) findViewById(R.id.ci);x.image().bind(circleImageView,url,new ImageOptions.Builder().setImageScaleType(ImageView.ScaleType.CENTER_CROP).build()
以上所述是小編給大家介紹的Android 自定義圓形頭像CircleImageView支持加載網絡圖片的實現代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答