【问题标题】:How to create a rectangle with rounded corners with different sections in different colors如何创建具有不同颜色的不同部分的圆角矩形
【发布时间】:2019-01-08 18:31:19
【问题描述】:

要求

如何创建这样的视图。

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

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

我尝试过的想法/事情

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

我尝试了一个自定义视图,它并排呈现 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
}

(2) 圆角形状

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

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

(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>

(4) 带角的图层列表??

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

<?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>

摘要

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

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

更新:如何添加海拔/灰色边框

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

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

我希望它如下所示

【问题讨论】:

    标签: android


    【解决方案1】:

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

    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);
    

    如果您将半透明的Paints 堆叠起来,同时减少描边宽度并增加插图,它也可以看起来不错(更多 3D),例如构建自己的颜色渐变。

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

    更改我的代码(注意:仅适用于 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));
    }
    

    【讨论】:

    • 谢谢你的回复,这看起来很有希望,我明天回去工作时好好看看。
    • 这可以根据需要完美运行。我缺少的是 onDraw 中的 onLyaout 和 clipPath 部分。非常感谢。
    • 知道如何添加高程使其看起来像 3D 或轻微的灰色边框。如果我添加 "android:elevation="2dp" android:outlineProvider="bounds" " 它是一个灰色的矩形阴影,我的弯角看起来很糟糕
    • 我已经更新了我的原始问题,以包含关于海拔的截图以及我想要实现的目标。提前致谢
    • @se22as - 您可以使用填充类型为 STROKE 的 Paint 绘制圆角矩形。我相应地编辑了我的答案。
    【解决方案2】:

    对于影子后续问题,您有两种选择。使用内置方法或自己绘制(取决于需要)。除非您需要自定义阴影,否则前者可能是正确的方法。

    内置方法

    请参阅此博客文章中的大纲部分: https://android.jlelse.eu/mastering-shadows-in-android-e883ad2c9d5b

    帖子中的示例代码:

    创建一个大纲提供者

    public class ScalingLayoutOutlineProvider extends ViewOutlineProvider {
    
        @Override
        public void getOutline(View view, Outline outline) {
            outline.setRoundRect(0, 0, width, height, radius);
        }
    }
    

    将大纲提供程序添加到您的视图中

    public class ScalingLayout extends FrameLayout {
    
        //...
        viewOutline = new ScalingLayoutOutlineProvider(w, h, currentRadius);
        setOutlineProvider(viewOutline);
        //..
    
    }
    

    自己画

    对于边框,您可以使用 View.getElevation() 来获得所需的高度:https://developer.android.com/reference/android/view/View#getElevation(),然后在栏后面绘制另一个形状作为阴影。

    【讨论】:

    • 谢谢@wblaschko,非常感谢
    【解决方案3】:

    例如(将颜色调整为所需的颜色、边距、高度等):

    您可以使用LinearLayout 作为具有horizontal 方向的根布局并分配一些weights,创建子布局并为其添加自定义背景。简单没有太多嵌套布局。

    例如:

    <?xml version="1.0" encoding="utf-8"?>
    

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_margin="20dp"
        android:orientation="horizontal">
    
        <LinearLayout
            android:id="@+id/statsLayout"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:clickable="true"
            android:background="@drawable/left_background">
    
            <TextView
                android:id="@+id/stats"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:text="A%"
                android:textAppearance="@style/TextAppearance.AppCompat.Title"
                android:textColor="@android:color/black" />
        </LinearLayout>
    
    
        <LinearLayout
            android:id="@+id/ncaaInfoLayout"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:clickable="true"
            android:background="@drawable/middle_background">
    
            <TextView
                android:id="@+id/ncaaInfo"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:text="B%"
                android:textAppearance="@style/TextAppearance.AppCompat.Title"
                android:textColor="@android:color/black" />
        </LinearLayout>
    
        <LinearLayout
            android:id="@+id/accountLayout"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:clickable="true"
            android:background="@drawable/right_background">
    
            <TextView
                android:id="@+id/account"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:text="C%"
                android:textAppearance="@style/TextAppearance.AppCompat.Title"
                android:textColor="@android:color/black" />
        </LinearLayout>
    </LinearLayout>
    

    比为每个孩子创建背景LinearLayout 为左一个left_bacground.xml

    <shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:bottomLeftRadius="30dp"
        android:topLeftRadius="30dp" />
    <solid android:color="@android:color/holo_green_dark" />
    

    LinearLayout in middlemiddle_background.xml`:

    <shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@android:color/holo_orange_dark" />
    

    最后一个LinearLayout代表右边right_bacgkround.xml

      <?xml version="1.0" encoding="utf-8"?>
     <shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:bottomRightRadius="30dp"
        android:topRightRadius="30dp" />
    <solid android:color="@android:color/holo_blue_dark" />
    

    【讨论】:

    • 感谢您的建议。但是,如果例如左侧颜色为 0% 并且因此不应显示,这将不起作用,因为现在中间颜色需要在其背景上指定的角。所以它回到了以编程方式指定任何颜色的圆角的问题
    • 您可以通过将布局的可见性从VISIBLE 更改为GONE 并从drawable 分配相应的background 来轻松设置它。我认为这是最简单的解决方案。
    【解决方案4】:

    你应该使用CardView看看这个例子:

    <androidx.cardview.widget.CardView
      android:layout_width="match_parent"
      android:layout_height="180dp"
      android:layout_margin="@dimen/activity_vertical_margin"
      app:cardPreventCornerOverlap="false"
      app:cardCornerRadius="@dimen/activity_vertical_margin"
      android:foreground="?android:attr/selectableItemBackground">
    
      <androidx.constraintlayout.widget.ConstraintLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content">
    
          <View
            android:id="@+id/view1"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:background="#0c21a9"
            app:layout_constraintWidth_percent="0.33"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent" />
    
          <View
            android:id="@+id/view2"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:background="#51c914"
            app:layout_constraintWidth_percent="0.33"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toEndOf="@id/view1" />
    
         <View
            android:id="@+id/view3"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:background="#a90c0c"
            app:layout_constraintWidth_percent="0.33"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toEndOf="@id/view2" />     
    
      </androidx.constraintlayout.widget.ConstraintLayout>     
    
    </androidx.cardview.widget.CardView> 
    

    此属性可防止圆角重叠app:cardPreventCornerOverlap="false"

    请注意,我使用的是 Google AndroidX 推荐的库 androidx。如果您愿意,可以使用旧版支持库。

    【讨论】:

    • 感谢您的建议,这看起来很有希望。我想我只需要设置每个子视图的宽度和可见性,主 CardView 标签是围绕整个视图角落的标签。
    • 是的,这可以帮助您设置宽度 app:layout_constraintWidth_percent="0.33" ConstraintLayout 有很多好处,您可以利用这些好处仅使用父级构建视图
    猜你喜欢
    • 2019-11-17
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 2013-10-08
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 2016-11-03
    相关资源
    最近更新 更多