在實現用戶頭像等需求的時候會用到圓形圖片的處理方法,在Android中沒有直接提供圓形圖片的控件則需要使用自定義控件實現圓形圖片的實現。
原理:主要使用SRC_IN這種模式來實現圖片的圓形效果。首先說一下SRC_IN的原理,PorterDuff.Mode一共有16種模式,SRC_IN是其中的一種,它是將Dst圖片與SRC圖片重疊獲得重疊的部分顯示的是SRC部分。也就是說首先使用它來實現圓形圖片的效果我們只要關心兩個圖片的draw的先後順序,先畫圓使用SRC_IN再畫圖片就可以得到原型圖片。畫邊線即爲在圖片外繪製一個帶邊線的空心圓。
下面是實現圓形圖片的核心代碼:
/**
* 根據原圖和變長繪製圓形圖片
*
* @param source
* @param min
* @return
*/
private Bitmap createCircleImage(Bitmap source, int min)
{
final Paint paint = new Paint();
paint.setAntiAlias(true);
Bitmap target = Bitmap.createBitmap(min, min, Config.ARGB_8888);
/**
* 產生一個同樣大小的畫布
*/
Canvas canvas = new Canvas(target);
/**
* 首先繪製圓形
*/
canvas.drawCircle(min / 2, min / 2, min / 2, paint);
/**
* 使用SRC_IN,參考上面的說明
*/
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
/**
* 繪製圖片
*/
canvas.drawBitmap(source, 0, 0, paint);
return target;
}
下面是一張PorterDuff.Mode16種模式的示意圖,可以根據需求進行選擇使用
畫邊線的核心代碼:
/**
* 邊緣畫圓
*/
private void drawCircleBorder(Canvas canvas, int radius, int color) {
Paint paint = new Paint();
/* 去鋸齒 */
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
paint.setColor(color);
/* 設置paint的 style 爲STROKE:空心 */
paint.setStyle(Paint.Style.STROKE);
/* 設置paint的外框寬度 */
paint.setStrokeWidth(mBorderThickness);
canvas.drawCircle(defaultWidth / 2, defaultHeight / 2, radius, paint);
}
繪製圖片圓角的效果使用的原理與圓形圖片相同,只是他首先繪製的是圓角,下面爲核心代碼:/**
* 根據原圖添加圓角
*
* @param source
* @return
*/
private Bitmap createRoundConerImage(Bitmap source)
{
final Paint paint = new Paint();
paint.setAntiAlias(true);
Bitmap target = Bitmap.createBitmap(defaultWidth, defaultHeight, Config.ARGB_8888);
Canvas canvas = new Canvas(target);
RectF rect = new RectF(0, 0, source.getWidth(), source.getHeight());
canvas.drawRoundRect(rect, mRadius, mRadius, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(source, 0, 0, paint);
return target;
}
使用自定義屬性來實現控制邊界線的顏色以及圓角的大小:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="roundedimageview">
<attr name="border_thickness" format="dimension" />
<attr name="border_inside_color" format="color" />
<attr name="border_outside_color" format="color"></attr>
<attr name="radius" format="dimension"></attr>
</declare-styleable>
</resources>
border_thickness用來設置邊界線的寬度,border_inside_color用來設置內邊界線的顏色,border_outside_color用來設置外邊界線的顏色,radius用來設置圓角圖片的圓角大小。當只設置一條邊線的顏色時,只顯示一條邊線,當不設置radius的值時則爲圓形圖片,當設置radius的時候則爲圓角圖片。
在佈局文件使用自定義控件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:test="http://schemas.android.com/apk/res/com.example.activityanimationdemo"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="click me"
tools:context=".MainActivity" />
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<com.example.activityanimationdemo.RoundImageView
android:id="@+id/mytest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="7.5dip"
android:layout_marginTop="9.5dip"
android:contentDescription="@string/app_name"
android:scaleType="center"
test:border_inside_color="@color/black"
test:border_outside_color="#fa9945"
test:border_thickness="1dp"
android:src="@drawable/work_active"
/>
<com.example.activityanimationdemo.RoundImageView
android:layout_below="@id/mytest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="7.5dip"
android:layout_marginTop="9.5dip"
android:contentDescription="@string/app_name"
android:scaleType="center"
test:border_inside_color="@color/black"
test:border_outside_color="#fa9945"
test:border_thickness="1dp"
android:src="@drawable/work_active"
test:radius="5dp"
/>
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btn"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:ems="10"
android:background="@drawable/orderleft_select"
android:inputType="textPostalAddress" >
<requestFocus />
</EditText>
</RelativeLayout>
自定義imageview:
public class RoundImageView extends ImageView {
private int mBorderThickness = 0;
private int mRadius=0;
private Context mContext;
private int defaultColor = 0xFFFFFFFF;
// 如果只有其中一個有值,則只畫一個圓形邊框
private int mBorderOutsideColor = 0;
private int mBorderInsideColor = 0;
// 控件默認長、寬
private int defaultWidth = 0;
private int defaultHeight = 0;
public RoundImageView(Context context) {
super(context);
mContext = context;
}
public RoundImageView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
setCustomAttributes(attrs);
}
public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
setCustomAttributes(attrs);
}
private void setCustomAttributes(AttributeSet attrs) {
TypedArray a = mContext.obtainStyledAttributes(attrs,R.styleable.roundedimageview);
mBorderThickness = a.getDimensionPixelSize(R.styleable.roundedimageview_border_thickness, 0);
mBorderOutsideColor = a.getColor(R.styleable.roundedimageview_border_outside_color,defaultColor);
mBorderInsideColor = a.getColor(R.styleable.roundedimageview_border_inside_color, defaultColor);
mRadius=a.getDimensionPixelSize(R.styleable.roundedimageview_radius, 0);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
if (getWidth() == 0 || getHeight() == 0) {
return;
}
this.measure(0, 0);
if (drawable.getClass() == NinePatchDrawable.class)
return;
Bitmap b = ((BitmapDrawable) drawable).getBitmap();
if (null != b) {
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
if (defaultWidth == 0) {
defaultWidth = getWidth();
}
if (defaultHeight == 0) {
defaultHeight = getHeight();
}
if(0!=mRadius){
canvas.drawBitmap(createRoundConerImage(b), 0, 0, null);
return;
}
// 保證重新讀取圖片後不會因爲圖片大小而改變控件寬、高的大小(針對寬、高爲wrap_content佈局的imageview,但會導致margin無效)
// if (defaultWidth != 0 && defaultHeight != 0) {
// LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
// defaultWidth, defaultHeight);
// setLayoutParams(params);
// }
int radius = 0;
if (mBorderInsideColor != defaultColor&& mBorderOutsideColor != defaultColor) {// 定義畫兩個邊框,分別爲外圓邊框和內圓邊框
radius = (defaultWidth < defaultHeight ? defaultWidth: defaultHeight) / 2 - 2 * mBorderThickness;
// 畫內圓
drawCircleBorder(canvas, radius + mBorderThickness / 2,mBorderInsideColor);
// 畫外圓
drawCircleBorder(canvas, radius + mBorderThickness+ mBorderThickness / 2, mBorderOutsideColor);
} else if (mBorderInsideColor != defaultColor&& mBorderOutsideColor == defaultColor) {// 定義畫一個邊框
radius = (defaultWidth < defaultHeight ? defaultWidth: defaultHeight) / 2 - mBorderThickness;
drawCircleBorder(canvas, radius + mBorderThickness / 2,mBorderInsideColor);
} else if (mBorderInsideColor == defaultColor&& mBorderOutsideColor != defaultColor) {// 定義畫一個邊框
radius = (defaultWidth < defaultHeight ? defaultWidth: defaultHeight) / 2 - mBorderThickness;
drawCircleBorder(canvas, radius + mBorderThickness / 2,mBorderOutsideColor);
} else {// 沒有邊框
radius = (defaultWidth < defaultHeight ? defaultWidth : defaultHeight) / 2;
}
Bitmap roundBitmap = getCroppedRoundBitmap(bitmap, radius);
canvas.drawBitmap(roundBitmap, defaultWidth / 2 - radius,defaultHeight / 2 - radius, null);
}
}
/**
* 獲取裁剪後的圓形圖片
*
* @param radius
* 半徑
*/
public Bitmap getCroppedRoundBitmap(Bitmap bmp, int radius) {
Bitmap scaledSrcBmp;
int diameter = radius * 2;
// 爲了防止寬高不相等,造成圓形圖片變形,因此截取長方形中處於中間位置最大的正方形圖片
int bmpWidth = bmp.getWidth();
int bmpHeight = bmp.getHeight();
int squareWidth = 0, squareHeight = 0;
int x = 0, y = 0;
Bitmap squareBitmap;
if (bmpHeight > bmpWidth) {// 高大於寬
squareWidth = squareHeight = bmpWidth;
x = 0;
y = (bmpHeight - bmpWidth) / 2;
// 截取正方形圖片
squareBitmap = Bitmap.createBitmap(bmp, x, y, squareWidth,squareHeight);
} else if (bmpHeight < bmpWidth) {// 寬大於高
squareWidth = squareHeight = bmpHeight;
x = (bmpWidth - bmpHeight) / 2;
y = 0;
squareBitmap = Bitmap.createBitmap(bmp, x, y, squareWidth,squareHeight);
} else {
squareBitmap = bmp;
}
if (squareBitmap.getWidth() != diameter|| squareBitmap.getHeight() != diameter) {
scaledSrcBmp = Bitmap.createScaledBitmap(squareBitmap, diameter,diameter, true);
} else {
scaledSrcBmp = squareBitmap;
}
Bitmap output = Bitmap.createBitmap(scaledSrcBmp.getWidth(),scaledSrcBmp.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
Paint paint = new Paint();
Rect rect = new Rect(0, 0, scaledSrcBmp.getWidth(),scaledSrcBmp.getHeight());
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
canvas.drawCircle(scaledSrcBmp.getWidth() / 2,scaledSrcBmp.getHeight() / 2, scaledSrcBmp.getWidth() / 2,paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(scaledSrcBmp, rect, rect, paint);
// bitmap回收(recycle導致在佈局文件XML看不到效果)
// bmp.recycle();
// squareBitmap.recycle();
// scaledSrcBmp.recycle();
bmp = null;
squareBitmap = null;
scaledSrcBmp = null;
return output;
}
/**
* 邊緣畫圓
*/
private void drawCircleBorder(Canvas canvas, int radius, int color) {
Paint paint = new Paint();
/* 去鋸齒 */
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
paint.setColor(color);
/* 設置paint的 style 爲STROKE:空心 */
paint.setStyle(Paint.Style.STROKE);
/* 設置paint的外框寬度 */
paint.setStrokeWidth(mBorderThickness);
canvas.drawCircle(defaultWidth / 2, defaultHeight / 2, radius, paint);
}
/**
* 根據原圖添加圓角
*
* @param source
* @return
*/
private Bitmap createRoundConerImage(Bitmap source)
{
final Paint paint = new Paint();
paint.setAntiAlias(true);
Bitmap target = Bitmap.createBitmap(defaultWidth, defaultHeight, Config.ARGB_8888);
Canvas canvas = new Canvas(target);
RectF rect = new RectF(0, 0, source.getWidth(), source.getHeight());
canvas.drawRoundRect(rect, mRadius, mRadius, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(source, 0, 0, paint);
return target;
}
}