public class CustomCardView extends CardView { float radius = SizeUtils.dp2px(5); Path path; public CustomCardView(Context context) { super(context); init(); } public CustomCardView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public CustomCardView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); RoundRectShape roundRectShape = new RoundRectShape(new float[]{radius, radius, radius, radius, 0, 0,0,0}, null, null); ShapeDrawable shapeDrawable = new ShapeDrawable(roundRectShape); shapeDrawable.getPaint().setColor(Color.WHITE); // 设置你想要的背景颜色 shapeDrawable.setBounds(0, 0, getWidth(), getHeight()); canvas.drawPath(path,new Paint()); shapeDrawable.draw(canvas); setBackground(shapeDrawable); } private void init() { path = new Path(); RectF rect = new RectF(0, 0, getWidth(), getHeight()); path.moveTo(0, 0); // 移动到左上角 path.lineTo(0, radius); // 绘制左上角的线 path.quadTo(0, 0, radius, 0); // 绘制左上角的圆角 path.lineTo(rect.right - radius, 0); // 绘制顶部右边的线 path.quadTo(rect.right, 0, rect.right, radius); // 绘制顶部右边的圆角 path.lineTo(rect.right, rect.bottom); // 绘制底部右边的线 path.lineTo(0, rect.bottom); // 绘制底部左边的线 path.close(); // 关闭路径 } public void setRadius(int number){ radius = SizeUtils.dp2px(number); invalidate(); } }
自定义CardView只实现top圆角
最新推荐文章于 2025-06-11 13:50:22 发布