1、在res/values文件夹下创建attrs.xml文件,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="RoundCornerView">
<attr name="cornerRadius" format="dimension" />
<attr name="src" format="integer" />
</declare-styleable>
</resources>
2、RoundCornerView类:
public class RoundCornerView extends View {
private Bitmap src;
private Bitmap roundCornerBitmap;
private float mRadius = 1; //圆角半径
public RoundCornerView(Context context) {
super(context);
}
public RoundCornerView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public RoundCornerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.RoundCornerView);
mRadius = ta.getDimension(R.styleable.RoundCornerView_cornerRadius, mRadius);
int resID = ta.getResourceId(R.styleable.RoundCornerView_src, 0);
src = BitmapFactory.decodeResource(getResources(), resID);
ta.recycle();
}
private Bitmap convertToRoundCornerBitmap() {
if (src == null)
return null;
int width;
int height;
LayoutParams lp = getLayoutParams();
if (lp != null && lp.width == LayoutParams.WRAP_CONTENT) { //处理View大小为wrap_content的情况
width = src.getWidth();
} else {
width = getWidth();
}
if (lp != null && lp.width == LayoutParams.WRAP_CONTENT) {
height = src.getHeight();
} else {
height = getHeight();
}
final Paint paint = new Paint();
paint.setAntiAlias(true);
Bitmap target = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Canvas canvas = new Canvas(target);
RectF rect = new RectF(0, 0, width, height);
canvas.drawRoundRect(rect, mRadius, mRadius, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); //图层的交集,显示上层
// Bitmap scaledSource = Bitmap.createScaledBitmap(source, width, height, true);
// canvas.drawBitmap(scaledSource, 0, 0, paint);
canvas.drawBitmap(src, null, new Rect(0, 0, width, height), paint); //该行代码和以上两句注释的代码作用相同,但是这里的好处是不用创建新的Bitmap
return target;
}
@Override
protected void onDraw(Canvas canvas) {
if (roundCornerBitmap == null) {
roundCornerBitmap = convertToRoundCornerBitmap();
}
if (roundCornerBitmap != null) {
canvas.drawBitmap(roundCornerBitmap, 0, 0, null);
}
}
}
3、在布局里显示该组件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:bobo="http://schemas.android.com/apk/res/com.example.bobo"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.bobo.RoundCornerView
android:layout_width="100dp"
android:layout_height="100dp"
bobo:cornerRadius="20dp"
bobo:src="@drawable/men_head"
android:layout_centerInParent="true" />
</RelativeLayout>
完成。效果如下:
转载自原文链接, 如需删除请联系管理员。
原文链接:android自定义圆角View组件,转载请注明来源!