圆角图片在现在的设计里,是非常常见的了,网上这方面的代码也非常多,
作为初学者,刚好有点时间,就想自己研究一下,
如果要求不高的话,其实还是挺简单的。
效果图:
直接上代码:
package com.example.labcirclebar;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
public class CircleImageView extends ImageView {
private int mWidth;
private int mHeight;
private int mRadius;
private Paint mBackgroundPaint;
private Path mPath;
private Drawable mDrawable = null;
public CircleImageView(Context context, AttributeSet attrs) {
super(context, attrs);
initPaint();
}
@Override
protected void onDraw(Canvas canvas) {
mDrawable = getDrawable() ;
if(mDrawable==null){
return;
}
mWidth = getWidth();
mHeight = getHeight();
mRadius = mWidth < mHeight ? mWidth/2 : mHeight/2;
// 先画背景
canvas.drawCircle(mRadius, mRadius, mRadius, mBackgroundPaint);
// 画一个圆形path,把图片画在画布的圆形上
canvas.save();
mPath.addCircle(mRadius, mRadius, mRadius-16, Path.Direction.CCW);
canvas.clipPath(mPath);
mDrawable.draw(canvas);
canvas.restore();
}
/**
* 设置画笔
*/
private void initPaint (){
mBackgroundPaint = new Paint();
mBackgroundPaint.setAntiAlias(true);
mBackgroundPaint.setStyle(Paint.Style.FILL);
mBackgroundPaint.setStrokeWidth(20);
mBackgroundPaint.setColor(Color.parseColor("#7FFFFFFF"));
mPath = new Path();
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:custom="http://schemas.android.com/apk/res/com.example.labcirclebar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@drawable/splash"
tools:context="com.example.labcirclebar.MainActivity" >
<com.example.labcirclebar.CircleImageView
android:id="@+id/circle_image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="@drawable/avatar" />
</RelativeLayout>