轉(zhuǎn)載請(qǐng)注明出處:http://blog.csdn.net/linglongxin24/article/details/52923384 【DylanAndroid的csdn博客】
在Android開發(fā)中我們常常用到圓形的頭像,如果每次加載之后再進(jìn)行圓形裁剪特別麻煩。所以在這里寫一個(gè)自定義圓形ImageView,直接去加載網(wǎng)絡(luò)圖片,這樣的話就特別的方便。
先上效果圖
這里寫圖片描述
主要的方法
1.讓自定義 CircleImageView 繼承ImageView
/**
* 自定義圓形頭像
* Created by Dylan on 2015/11/26 0026.
*/
public class CircleImageView extends ImageView {
}
2.在構(gòu)造方法中獲取在xml中設(shè)置的值
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.初始化各種參數(shù)設(shè)置
/**
* 畫圓形圖的初始化工作
*/
private void setup() {
if (!mReady) {
mSetupPending = true;
return;
}
if (mBitmap == null) {
return;
}
/**
*調(diào)用這個(gè)方法來產(chǎn)生一個(gè)畫有一個(gè)位圖的渲染器(Shader)。
bitmap 在渲染器內(nèi)使用的位圖
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 :如果渲染器超出原始邊界范圍,會(huì)復(fù)制范圍內(nèi)邊緣染色。
REPEAT :橫向和縱向的重復(fù)渲染器圖片,平鋪。
MIRROR :橫向和縱向的重復(fù)渲染器圖片,這個(gè)和REPEAT 重復(fù)方式不一樣,他是以鏡像方式平鋪。
*/
mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
/**
* 設(shè)置畫圓形的畫筆
*/
mBitmapPaint.setAntiAlias(true);//設(shè)置抗鋸齒
mBitmapPaint.setShader(mBitmapShader);//繪制圖形時(shí)的圖形變換
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setAntiAlias(true);
mBorderPaint.setColor(mBorderColor);
mBorderPaint.setStrokeWidth(mBorderWidth);
mBitmapHeight = mBitmap.getHeight();
mBitmapWidth = mBitmap.getWidth();
/**
* 設(shè)置邊框矩形的坐標(biāo)
*/
mBorderRect.set(0, 0, getWidth(), getHeight());
/**
* 設(shè)置邊框圓形的半徑為圖片的寬度和高度的一半的最大值
*/
mBorderRadius = Math.max((mBorderRect.height() - mBorderWidth) / 2, (mBorderRect.width() - mBorderWidth) / 2);
/**
* 設(shè)置圖片矩形的坐標(biāo)
*/
mDrawableRect.set(mBorderWidth, mBorderWidth, mBorderRect.width() - mBorderWidth, mBorderRect.height() - mBorderWidth);
/**
* 設(shè)置圖片圓形的半徑為圖片的寬度和高度的一半的最大值
*/
mDrawableRadius = Math.max(mDrawableRect.height() / 2, mDrawableRect.width() / 2);
updateShaderMatrix();
/**
* 調(diào)用onDraw()方法進(jìn)行繪畫
*/
invalidate();
}
/**
* 更新位圖渲染
*/
private void updateShaderMatrix() {
float scale;
float dx = 0;
float dy = 0;
/**
* 重置
*/
mShaderMatrix.set(null);
/**
*計(jì)算縮放比,因?yàn)槿绻麍D片的尺寸超過屏幕,那么就會(huì)自動(dòng)匹配到屏幕的尺寸去顯示。
* 確定移動(dòng)的xy坐標(biāo)
*
*/
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);
/**
* 設(shè)置shader的本地矩陣
*/
mBitmapShader.setLocalMatrix(mShaderMatrix);
}
4.畫圓
@Override
protected 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 {
/**
* 圓形頭像默認(rèn),CENTER_CROP!=系統(tǒng)默認(rèn)的CENTER_CROP;
* 將圖片等比例縮放,讓圖像的長邊邊與ImageView的邊長度相同,短邊不夠的留空白,縮放后截取圓形部分進(jìn)行顯示。
*/
private static final ScaleType SCALE_TYPE = ScaleType.CENTER_CROP;
/**
* 圖片的壓縮質(zhì)量
* ALPHA_8就是Alpha由8位組成,------ALPHA_8 代表8位Alpha位圖
* ARGB_4444就是由4個(gè)4位組成即16位,------ARGB_4444 代表16位ARGB位圖
* ARGB_8888就是由4個(gè)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;
/**
* 默認(rèn)ColorDrawable的寬和高
*/
private static final int COLORDRAWABLE_DIMENSION = 1;
/**
* 默認(rèn)邊框?qū)挾? */
private static final int DEFAULT_BORDER_WIDTH = 0;
/**
* 默認(rèn)邊框顏色
*/
private static final int DEFAULT_BORDER_COLOR = Color.BLACK;
/**
* 畫圖片的矩形
*/
private final RectF mDrawableRect = new RectF();
/**
* 畫邊框的矩形
*/
private final RectF mBorderRect = new RectF();
/**
* 對(duì)圖片進(jìn)行縮放和移動(dòng)的矩陣
*/
private final Matrix mShaderMatrix = new Matrix();
/**
* 畫圖片的畫筆
*/
private final Paint mBitmapPaint = new Paint();
/**
* 畫邊框的畫筆
*/
private final Paint mBorderPaint = new Paint();
/**
* 默認(rèn)邊框顏色
*/
private int mBorderColor = DEFAULT_BORDER_COLOR;
/**
* 默認(rèn)邊框?qū)挾? */
private int mBorderWidth = DEFAULT_BORDER_WIDTH;
private Bitmap mBitmap;
/**
* 產(chǎn)生一個(gè)畫有一個(gè)位圖的渲染器(Shader)
*/
private BitmapShader mBitmapShader;
/**
* 圖片的實(shí)際寬度
*/
private int mBitmapWidth;
/**
* 圖片實(shí)際高度
*/
private int mBitmapHeight;
/**
* 圖片半徑
*/
private float mDrawableRadius;
/**
* 邊框半徑
*/
private float mBorderRadius;
/**
* 是否初始化準(zhǔn)備好
*/
private boolean mReady;
/**
* 內(nèi)邊距
*/
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;
}
}
@Override
public ScaleType getScaleType() {
return SCALE_TYPE;
}
@Override
protected void onDraw(Canvas canvas) {
if (getDrawable() == null) {
return;
}
/**
* 畫圓形圖片
*/
canvas.drawCircle(getWidth() / 2, getHeight() / 2, mDrawableRadius, mBitmapPaint);
/**
* 畫圓形邊框
*/
canvas.drawCircle(getWidth() / 2, getHeight() / 2, mBorderRadius, mBorderPaint);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
setup();
}
/**
* 獲取邊框顏色
*
* @return
*/
public int getBorderColor() {
return mBorderColor;
}
/**
* 設(shè)置邊框顏色
*
* @param borderColor
*/
public void setBorderColor(int borderColor) {
if (borderColor == mBorderColor) {
return;
}
mBorderColor = borderColor;
mBorderPaint.setColor(mBorderColor);
invalidate();
}
/**
* 獲取邊框?qū)挾? *
* @return
*/
public int getBorderWidth() {
return mBorderWidth;
}
/**
* 設(shè)置邊框?qū)挾? *
* @param borderWidth
*/
public void setBorderWidth(int borderWidth) {
if (borderWidth == mBorderWidth) {
return;
}
mBorderWidth = borderWidth;
setup();
}
/**
* 設(shè)置資源圖片
*
* @param bm
*/
@Override
public void setImageBitmap(Bitmap bm) {
super.setImageBitmap(bm);
mBitmap = bm;
setup();
}
/**
* 設(shè)置資源圖片
*
* @param drawable
*/
@Override
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
mBitmap = getBitmapFromDrawable(drawable);
setup();
}
/**
* 設(shè)置資源id
*
* @param resId
*/
@Override
public 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;
}
/**
*調(diào)用這個(gè)方法來產(chǎn)生一個(gè)畫有一個(gè)位圖的渲染器(Shader)。
bitmap 在渲染器內(nèi)使用的位圖
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 :如果渲染器超出原始邊界范圍,會(huì)復(fù)制范圍內(nèi)邊緣染色。
REPEAT :橫向和縱向的重復(fù)渲染器圖片,平鋪。
MIRROR :橫向和縱向的重復(fù)渲染器圖片,這個(gè)和REPEAT 重復(fù)方式不一樣,他是以鏡像方式平鋪。
*/
mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
/**
* 設(shè)置畫圓形的畫筆
*/
mBitmapPaint.setAntiAlias(true);//設(shè)置抗鋸齒
mBitmapPaint.setShader(mBitmapShader);//繪制圖形時(shí)的圖形變換
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setAntiAlias(true);
mBorderPaint.setColor(mBorderColor);
mBorderPaint.setStrokeWidth(mBorderWidth);
mBitmapHeight = mBitmap.getHeight();
mBitmapWidth = mBitmap.getWidth();
/**
* 設(shè)置邊框矩形的坐標(biāo)
*/
mBorderRect.set(0, 0, getWidth(), getHeight());
/**
* 設(shè)置邊框圓形的半徑為圖片的寬度和高度的一半的最大值
*/
mBorderRadius = Math.max((mBorderRect.height() - mBorderWidth) / 2, (mBorderRect.width() - mBorderWidth) / 2);
/**
* 設(shè)置圖片矩形的坐標(biāo)
*/
mDrawableRect.set(mBorderWidth, mBorderWidth, mBorderRect.width() - mBorderWidth, mBorderRect.height() - mBorderWidth);
/**
* 設(shè)置圖片圓形的半徑為圖片的寬度和高度的一半的最大值
*/
mDrawableRadius = Math.max(mDrawableRect.height() / 2, mDrawableRect.width() / 2);
updateShaderMatrix();
/**
* 調(diào)用onDraw()方法進(jìn)行繪畫
*/
invalidate();
}
/**
* 更新位圖渲染
*/
private void updateShaderMatrix() {
float scale;
float dx = 0;
float dy = 0;
/**
* 重置
*/
mShaderMatrix.set(null);
/**
*計(jì)算縮放比,因?yàn)槿绻麍D片的尺寸超過屏幕,那么就會(huì)自動(dòng)匹配到屏幕的尺寸去顯示。
* 確定移動(dòng)的xy坐標(biāo)
*
*/
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);
/**
* 設(shè)置shader的本地矩陣
*/
mBitmapShader.setLocalMatrix(mShaderMatrix);
}
}
2.里面所使用到的ImageSizeUtil
public class ImageSizeUtil
{
/**
* 根據(jù)ImageView獲適當(dāng)?shù)膲嚎s的寬和高
*
* @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的實(shí)際寬度
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的實(shí)際高度
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.CircleImageView
android: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());