本文主要是介绍CardView设置任意角为圆角,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
注意:material:1.1.0以上版本在RadiusCardView节点下一定要添加 android:theme=“@style/Theme.MaterialComponents”,不然会报错,另外,由于是重写自MaterialCardView,所以一定要导入material包:
implementation 'com.google.android.material:material:1.1.0'
样式:
源码:
RadiusCardView
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Region;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;import com.google.android.material.card.MaterialCardView;
import com.seocoo.user.R;public class RadiusCardView extends MaterialCardView {private float tlRadiu;private float trRadiu;private float brRadiu;private float blRadiu;public RadiusCardView(Context context) {this(context, null);}public RadiusCardView(Context context, AttributeSet attrs) {this(context, attrs, R.attr.materialCardViewStyle);}public RadiusCardView(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);setRadius(0);TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RadiusCardView);tlRadiu = array.getDimension(R.styleable.RadiusCardView_rcv_topLeftRadiu, 0);trRadiu = array.getDimension(R.styleable.RadiusCardView_rcv_topRightRadiu, 0);brRadiu = array.getDimension(R.styleable.RadiusCardView_rcv_bottomRightRadiu, 0);blRadiu = array.getDimension(R.styleable.RadiusCardView_rcv_bottomLeftRadiu, 0);setBackground(new ColorDrawable());}@Overrideprotected void onDraw(Canvas canvas) {Path path = new Path();RectF rectF = getRectF();float[] readius = {tlRadiu,tlRadiu,trRadiu,trRadiu,brRadiu,brRadiu,blRadiu,blRadiu};path.addRoundRect(rectF,readius,Path.Direction.CW);canvas.clipPath(path,Region.Op.INTERSECT);super.onDraw(canvas);}private RectF getRectF() {Rect rect = new Rect();getDrawingRect(rect);RectF rectF = new RectF(rect);return rectF;}
}
attr文件:
<declare-styleable name="RadiusCardView"><!-- 左上圆角大小--><attr name="rcv_topLeftRadiu" format="dimension" /><!-- 右上圆角大小--><attr name="rcv_topRightRadiu" format="dimension" /><!-- 右下圆角大小--><attr name="rcv_bottomRightRadiu" format="dimension" /><!-- 左下圆角大小--><attr name="rcv_bottomLeftRadiu" format="dimension" /></declare-styleable>
使用案例:
<RadiusCardView所在路径.RadiusCardViewandroid:layout_width="match_parent"android:layout_height="200dp"android:theme="@style/Theme.MaterialComponents" //这行一定要添加,不然会报错app:rcv_topLeftRadiu="20dp"app:rcv_topRightRadiu="40dp"app:rcv_bottomLeftRadiu="10dp"app:rcv_bottomRightRadiu="60dp"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"><Viewandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="2"android:background="@color/color295C8E"/><Viewandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"android:background="@color/color9E7900"/></LinearLayout></RadiusCardView所在路径.RadiusCardView>
这篇关于CardView设置任意角为圆角的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!