您的位置:首页 > 移动开发 > Android开发

Android仿QQ圆形头像

2015-03-17 17:39 323 查看
先上效果图:



实现思路:

        自定义一个View,继承ImageView,通过PorterDuffXfermode实现一个Mask效果,并在onDraw中画出来。

自定义View的代码:

public class CircleClipView extends ImageView{

private Paint backgroundPaint = null;
private Paint maskPaint = null;

private int backgroundColor = -1;

public CircleClipView(Context context) {
// TODO Auto-generated constructor stub
super(context);
init();
}

public CircleClipView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.circleview);
backgroundColor = a.getColor(R.styleable.circleview_backgroundcolor, Color.WHITE);
a.recycle();
init();
}

private void init(){
maskPaint = new Paint();
PorterDuffXfermode porterDuffXfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN);
maskPaint.setXfermode(porterDuffXfermode);
maskPaint.setColor(Color.TRANSPARENT);
maskPaint.setAntiAlias(true);

backgroundPaint = new Paint();
backgroundPaint.setColor(backgroundColor);
backgroundPaint.setAntiAlias(true);

}

private Bitmap getMask(){
Bitmap b = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(b);
RectF rectF = new RectF(0, 0, getWidth(), getHeight());
canvas.drawRect(rectF, backgroundPaint);
canvas.drawOval(rectF, maskPaint);
return b;
}

private Bitmap scaleDrawable(Drawable drawable){
Bitmap b = ((BitmapDrawable) drawable).getBitmap();
Matrix matrix = new Matrix();
float scaleWidth = ((float) getWidth()) / b.getWidth();
float scaleHeight = ((float) getHeight()) / b.getHeight();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap bitmap = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(),matrix, true);
return bitmap;
}

@Override
protected void onDraw(Canvas canvas)
{
Bitmap sourceBitmap = scaleDrawable(getDrawable());
if(sourceBitmap != null) canvas.drawBitmap(sourceBitmap, 0, 0, null);
canvas.drawBitmap(getMask(), 0, 0, null);
}
}


XML代码
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res/com.rfjr.first"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >

<com.rfjr.first.view.CircleClipView
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/icon"
myapp:backgroundcolor="#ffffff" />

</RelativeLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android 界面 qq