如何在运行时用代码设置View单个corner的圆角弧度

前言

说起这个圆角,大家都是会心一笑:“这谁没玩儿过”。
是的,在Android中有相当多的办法实现"上下左右"同时圆角。
为什么我要强调一下"上下左右" 呢?

还是让我们先回顾一下之前设置圆角的常规操作吧。

常规思路

1. 在xml配置圆角

就像下面这样

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:topLeftRadius="12dp"
        android:topRightRadius="12dp"
        />
    <solid android:color="#ffffff" />
</shape>

想要哪个角变成圆角都可以。so easy~
但是这样有一个缺点,如果我要在运行时动态改变圆角度数或者背景色怎么办?这就引出了下面的方式。

2. 运行时设定圆角

这个说来方法就很多了。大概有:

其他还有几种不怎么常用的。这里就不一一列举了。
但是我发现大家似乎都忽略了一种情况。就是


1. 只要求view的四个角中某一个或者几个角设置圆角,剩余的角都不动。
2. 背景色要在运行时修改。

简单讲,就是这个样子:


示意图.png

上图中,“新建分组”文案就只有topLeft和topRight两个角是圆角矩形的。

方案

简单讲:就是利用ShapeDrawableRoundRectShape。代码如下:

 private ShapeDrawable getTopCornorDrawable(int strokeColor) {
        //要设置的圆角弧度
        float radius = CommonDisplayUtils.transDP2PX(getContext(), 12);
        //圆角的半径。分别为:左上x、y, 右上x、y, 右下x、y,左下x、y
        float[] outerR = new float[]{radius, radius, radius, radius, 0, 0, 0, 0};

        RoundRectShape rr = new RoundRectShape(outerR, null, null);
        ShapeDrawable drawable = new ShapeDrawable(rr);
        drawable.getPaint().setColor(strokeColor);
        drawable.getPaint().setStyle(Paint.Style.FILL_AND_STROKE);
        drawable.getPaint().setStrokeWidth(1);
        return drawable;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容