android定义圆角layout,Android布局切圆角

本文介绍了如何在Android中自定义FrameLayout以实现为布局的每个角落设置不同圆角的方法。通过创建CornerFrameLayout并重写onDraw和onSizeChanged方法,可以自由指定每个角的弧度,满足特定需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、前言:

通常,要想使布局文件以圆角方式显示,最简便的方式是通过CardView进行包装。但是CardView设置圆角后四个角都是同样的弧度,有时候我们接到的需求是指给其中某些角指定圆角,或者给每个角指定不同的弧度,CardView就无法满足了。

以下代码便可实现该功能,给任意角指定任意弧度:

1、自定义FrameLayout

/**

* corner FrameLayout.you can control radius of every corner.

*

* @author gongshoudao

*/

public class CornerFrameLayout extends FrameLayout {

private final float[] mRadii = new float[8];

private final Path mPath = new Path();

public CornerFrameLayout(Context context, AttributeSet attrs) {

super(context, attrs);

}

@Override

protected void onDraw(Canvas canvas) {

super.onDraw(canvas);

if (!mPath.isEmpty()) {

canvas.clipPath(mPath);

}

}

@Override

protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {

super.onSizeChanged(width, height, oldWidth, oldHeight);

mPath.reset();

mPath.addRoundRect(new RectF(0, 0, width, height), mRadii, Path.Direction.CW);

}

/**

* set each corner radius.

*

* @param topLeft top left corner radius.

* @param topRight top right corner radius.

* @param bottomRight bottom right radius.

* @param bottomLeft bottom right radius.

*/

public void setRadius(float topLeft, float topRight, float bottomRight, float bottomLeft) {

mRadii[0] = topLeft;

mRadii[1] = topLeft;

mRadii[2] = topRight;

mRadii[3] = topRight;

mRadii[4] = bottomRight;

mRadii[5] = bottomRight;

mRadii[6] = bottomLeft;

mRadii[7] = bottomLeft;

invalidate();

}

/**

* set each corner radius.

*

* @param topLeftX top left X

* @param topLeftY top left y

* @param topRightX top right x

* @param topRightY top right y

* @param bottomRightX bottom right x

* @param bottomRightY bottom right y

* @param bottomLeftX bottom left x

* @param bottomLeftY bottom left y

*/

public void setRadius(float topLeftX, float topLeftY, float topRightX, float topRightY,float bottomRightX, float bottomRightY, float bottomLeftX, float bottomLeftY) {

mRadii[0] = topLeftX;

mRadii[1] = topLeftY;

mRadii[2] = topRightX;

mRadii[3] = topRightY;

mRadii[4] = bottomRightX;

mRadii[5] = bottomRightY;

mRadii[6] = bottomLeftX;

mRadii[7] = bottomLeftY;

invalidate();

}

}

2、使用:

android:id="@+id/h5_game_corner_container"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="@color/transparent"

android:clipChildren="true">

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值