android - 如何创建具有不同颜色不同部分的圆角矩形

标签 android

要求

如何创建这样的 View 。

enter image description here

我想在屏幕上绘制一个 View ,它是一条线,分成几段,显示整个 View 的值百分比。我的要求是

  • View 有不同颜色的不同部分
  • View 可能没有呈现所有部分,它可能只有前 2 个或第一个和最后一个或只有一种颜色等 - 这仅在运行时才知道
  • 不同部分的大小仅在运行时已知,因此需要以编程方式指定
  • 整个 View 的左右角都是圆的

我尝试过的想法/事情

(1)自定义 View 渲染3个矩形并排

我尝试了一个自定义 View ,它并排呈现 3 个矩形。但是这些显然有方角。

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    int viewHeight = 50;

    canvas.drawrect(0,  0, 60,  viewHeight, paint); // A
    canvas.drawrect(60, 0, 120, viewHeight, paint); // B
    canvas.drawrect(120,0, 180, viewHeight, paint); // C
}

enter image description here

(2) 圆角形状

我知道我可以使用 Shape 来定义带有圆角的矩形,但这是单一颜色。

<shape xmlns:android="http://schemas.android.com/apk/res/android">
     ...        
    <corners
        android:radius="4dp" />
    ....
</shape>

enter image description here

(3)图层列表

来自 Android rectangle shape with two different color ,我看到我可以使用图层列表来指定形状中的每个项目具有不同的颜色。

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">       

    <item>
        <shape android:shape="rectangle">
            <size
                android:width="40dp"
                android:height="40dp" />
            <solid android:color="#F86F05" />
        </shape>
    </item>

    <item android:top="10dp">
        <shape android:shape="rectangle">
            <size
                android:width="30dp"
                android:height="30dp" />
            <solid android:color="#B31F19" />
        </shape>
    </item>

</layer-list>

enter image description here

(4) Layer-list with corners??

我可以将“corners”标签添加到整个图层列表以获得圆形的主角吗?我假设不是,角落部分必须在“项目”的形状标签中。

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <corners
        android:radius="4dp" />

    <item>
        <shape android:shape="rectangle">
            <size
                android:width="40dp"
                android:height="40dp" />
            <solid android:color="#F86F05" />
        </shape>
    </item>

    <item android:top="10dp">
        <shape android:shape="rectangle">
            <size
                android:width="30dp"
                android:height="30dp" />
            <solid android:color="#B31F19" />
        </shape>
    </item>

</layer-list>

enter image description here

总结

不过这最后一个越来越接近我的要求了

  • 如何以编程方式指定每个“项目”的宽度
  • 如何以编程方式显示/隐藏“项目”
  • 我如何将最明显的“项目”的顶角和最底部的“项目”的底角四舍五入

更新:如何添加高度/灰色边框

感谢“@0X0nosugar”提供的解决方案。我现在想添加一个高程或轻微的灰色边框,因为其中一种颜色是故障灯并且接近背景颜色。当我添加以下内容时,我得到一个矩形阴影,它的角看起来很糟糕。

android:elevation="2dp"
android:outlineProvider="bounds"

enter image description here

我希望它看起来像下面这样

enter image description here

最佳答案

您可以创建自定义 View,它将在 Canvas 的裁剪部分上绘制矩形:

enter image description here

public class RoundedCornersSegmentedView extends View {

    private Paint paintA, paintB, paintC;
    private float cornerRadius;
    private float measuredWidth, measuredHeight;
    private RectF rect = new RectF(0, 0, 0,0);
    private Path rectPath = new Path();

    public RoundedCornersSegmentedView(Context context) {
        super(context);
        init();
    }

    public RoundedCornersSegmentedView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public RoundedCornersSegmentedView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setWillNotDraw(false);

        // add this so Canvas.clipPath() will give the desired result also for devices running Api level lower than 17,
        // see https://stackoverflow.com/a/30354461/5015207
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            setLayerType(LAYER_TYPE_SOFTWARE, null);
        }
        paintA = new Paint(Paint.ANTI_ALIAS_FLAG);
        paintA.setColor(Color.GREEN);
        paintA.setStyle(Paint.Style.FILL);
        paintB = new Paint(Paint.ANTI_ALIAS_FLAG);
        paintB.setColor(Color.YELLOW);
        paintB.setStyle(Paint.Style.FILL);
        paintC = new Paint(Paint.ANTI_ALIAS_FLAG);
        paintC.setColor(Color.MAGENTA);
        paintC.setStyle(Paint.Style.FILL);

        // with  <dimen name="corner_radius">60dp</dimen> in res/values/dimens.xml
        cornerRadius = getResources().getDimensionPixelSize(R.dimen.corner_radius);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        measuredWidth = right - left;
        measuredHeight = bottom - top;
        rect.set(0, 0, measuredWidth, measuredHeight);
        rectPath.reset();
        rectPath.addRoundRect(rect, cornerRadius, cornerRadius, Path.Direction.CW);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.clipPath(rectPath);
        canvas.drawRect(0,0,measuredWidth/3f, measuredHeight, paintA);
        canvas.drawRect(measuredWidth/3f,0,2 * measuredWidth/3f, measuredHeight, paintB);
        canvas.drawRect(2 * measuredWidth/3f,0,measuredWidth, measuredHeight, paintC);
    }
}

如果要添加某种半透明边缘,可以使用具有透明颜色和填充类型 Paint.Style.STROKEPaint 并绘制一个圆角矩形。

Paint shadowPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
// material color "Blue Gray 400",
// see https://material.io/design/color/the-color-system.html
shadowPaint.setColor(Color.argb(30, 120, 144, 156));
shadowPaint.setStyle(Paint.Style.STROKE);
shadowPaint.setStrokeWidth(30);

矩形(在 onLayout() 之外实例化以获得更好的性能):

private RectF shadowRect = new RectF(0,0,0,0);

onLayout() 中:

int inset = 20;
shadowRect.set(inset, inset, measuredWidth - inset, measuredHeight - inset);

您应该切换阴影 Paint 的颜色/alpha 值以及笔划宽度和插图的值,直到您认为它看起来不错。

在绘制彩色线段后在 onDraw() 中应用:

canvas.drawRoundRect(shadowRect, cornerRadius, cornerRadius, shadowPaint);

enter image description here

如果您堆叠半透明 Paint 并减少笔划宽度并增加插入,它也可以看起来不错(更 3D),例如构建您自己的颜色渐变。

感谢@wblaschko 在 ViewOutlineProvider 上分享代码 fragment ! 我将它添加到我的示例中并获得了以下效果:

enter image description here

更改我的代码(注意:仅适用于 Api 级别 21+)

自定义 View 的内部类:

@TargetApi(21)
static class ScalingOutlineProvider extends ViewOutlineProvider {
    private int cornerRadius;
    ScalingOutlineProvider(int cornerRadius){
        this.cornerRadius = cornerRadius;
    }
    @Override
    public void getOutline(View view, Outline outline) {
        outline.setRoundRect(0, 0, view.getWidth(), view.getHeight (), cornerRadius);
    }
}

init() 的末尾:

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
    // elevation of 4dp (cornerRadius was 60dp)
    setElevation(cornerRadius/15);
    setOutlineProvider(new ScalingOutlineProvider(cornerRadius));
}

关于android - 如何创建具有不同颜色不同部分的圆角矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54097662/

相关文章:

android - 我可以将 native GoogleMap 添加到我的 Cordova 混合应用程序吗?

java - Android ListActivity 与位图和垃圾收集问题

java - Android Studio 无法识别 EncryptedSharedPreferences 导入

android - 如何将新行动态添加到表格布局

android - 如何使用选择器更改 ImageButton 图像?

android - 更新时列出崩溃的应用程序

Android - 修正 onTouchEvent() 中状态栏的高度

android - 从 iOS 应用调用时, native Web RTC 视频通话在 Android 上卡住

android - 如何在 Android Studio 上创建 jniLibs 文件夹?

android - 抑制字段注释