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

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

作者: 一个搬砖小能手 | 来源:发表于2019-05-24 20:18 被阅读0次

前言

说起这个圆角,大家都是会心一笑:“这谁没玩儿过”。
是的,在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;
    }

相关文章

网友评论

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

      本文链接:https://www.haomeiwen.com/subject/efinzqtx.html