【问题标题】:How to make layout with rounded corners..?如何制作带圆角的布局..?
【发布时间】:2013-04-16 04:49:53
【问题描述】:

如何制作带有圆角的布局?我想为我的LinearLayout 应用圆角。

【问题讨论】:

  • 您只需将圆形图像设置为布局的背景,否则按照第一条评论中所述进行形状
  • 你只需要搜索SO...你会发现很多asnwers ..
  • 角落对我来说是模糊的
  • 谷歌有新框架,新技术更好Jetpack Compose

标签: android xml image layout android-shapedrawable


【解决方案1】:

如果您想要的只是一个简单的圆角矩形,那就长话短说吧。

float r=8;
ShapeDrawable shape = new ShapeDrawable (new RoundRectShape(new float[] { r, r, r, r, r, r, r, r },null,null));
shape.getPaint().setColor(Color.RED);
view.setBackground(shape);

更多详情请阅读this answer

【讨论】:

    【解决方案2】:

    第一步:在drawables文件夹中定义bg_layout.xml,并在其中放入如下代码。

    第 2 步:将 bg_layout.xml 作为背景添加到您的布局中,完成。

        <?xml version="1.0" encoding="UTF-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android">
        <solid
            android:color="#EEEEEE"/> <!--your desired colour for solid-->
    
        <stroke
            android:width="3dp"
            android:color="#EEEEEE" /> <!--your desired colour for border-->
    
        <corners
            android:radius="50dp"/> <!--shape rounded value-->
    
    </shape>
    

    【讨论】:

      【解决方案3】:

      我参加聚会有点晚了,但这仍然是个问题。所以我写了一组 OutlineProviders 和 BindingAdapters 用于数据绑定,可以让你从 xml 中裁剪角。

      注意:带轮廓的剪裁不支持不同大小的角!

      我在this stackoverflow post上写了详细的回复代码

      使用代码 + 绑定适配器你会得到什么:

      <androidx.constraintlayout.widget.ConstraintLayout
          clipRadius="@{@dimen/some_radius}"
          clipBottomLeft="@{@dimen/some_radius}"
          clipBottomRight="@{@dimen/some_radius}"
          clipTopLeft="@{@dimen/some_radius}"
          clipTopRight="@{@dimen/some_radius}"
          clipCircle="@{@bool/clip}"
      

      这使您可以将视图裁剪为圆形、圆角、一个方向的圆角(左、上、右、下)或单个角。

      【讨论】:

      • 如果你只是想要一个圆角的背景,这太过分了,你最好使用可绘制的 xml。但是,如果你想在不突出图像的情况下修整布局的角落,这就是方法。
      【解决方案4】:

      您可以使用自定义视图来执行此操作,例如 RoundAppBarRoundBottomAppBar。 这里path 用于clipPath 画布。

      【讨论】:

        【解决方案5】:

        对于 API 21+,使用剪辑视图

        圆形轮廓剪裁已添加到 API 21 中的 View 类中。有关详细信息,请参阅此 training doc 或此 reference

        此内置功能使圆角非常容易实现。它适用于任何视图或布局,并支持正确的剪辑。

        这是怎么做的:

        • 创建一个圆形可绘制对象并将其设置为视图的背景: android:background="@drawable/round_outline"
        • 剪辑到代码中的轮廓:setClipToOutline(true)

        文档曾经说您可以将android:clipToOutline="true" 设置为 XML,但 this bug 现在终于解决了,并且文档现在正确地指出您只能在代码中执行此操作。

        外观:

        关于 ImageViews 的特别说明

        setClipToOutline() 仅在 View 的背景设置为可绘制形状时有效。如果存在此背景形状,View 会将背景的轮廓视为边界,以进行剪切和阴影处理。

        这意味着,如果您想使用setClipToOutline() 对 ImageView 上的角进行圆角处理,则您的图像必须来自 android:src 而不是 android:background(因为背景用于圆角形状)。如果您必须使用背景而不是 src 来设置图像,则可以使用此嵌套视图解决方法:

        • 创建一个外部布局,其背景设置为可绘制的形状
        • 将该布局包裹在您的 ImageView 周围(没有填充)
        • ImageView(包括布局中的任何其他内容)现在将被裁剪为外部布局的圆形。

        【讨论】:

        • 不适用于低于 21 的 API。不能等到我只能支持 API 21。
        • 使用 'setClipToOutline' 有效,但它也会删除框架本身(用于背景的可绘制对象)。有什么办法可以避免吗?
        • 您是否阅读了我关于使用src=@drawable... 而不是background=@drawable 的说明?您可以这样做,也可以将 ImageView 嵌套在包含形状轮廓的容器视图中。
        • 每个人都在评论那个错误——它已经快三年了,而且在这十年中的任何时候都没有得到修复的迹象。让我们施加一些压力。
        • @FebinMathew 你不能。
        【解决方案6】:

        借助材质组件库,您可以使用 MaterialShapeDrawabledraw custom shapes

        只需将 LinearLayout 放入您的 xml 布局中即可:

        <LinearLayout
            android:id="@+id/linear_rounded"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            ..>
        
            <!-- content ..... -->
        
        </LinearLayout>
        

        然后您可以在您的代码中应用ShapeAppearanceModel。比如:

        float radius = getResources().getDimension(R.dimen.default_corner_radius);
        
        LinearLayout linearLayout= findViewById(R.id.linear_rounded);
        ShapeAppearanceModel shapeAppearanceModel = new ShapeAppearanceModel()
            .toBuilder()
            .setAllCorners(CornerFamily.ROUNDED,radius)
            .build();
        
        MaterialShapeDrawable shapeDrawable = new MaterialShapeDrawable(shapeAppearanceModel);
        //Fill the LinearLayout with your color
        shapeDrawable.setFillColor(ContextCompat.getColorStateList(this,R.color.secondaryLightColor));
        
        
        ViewCompat.setBackground(linearLayout,shapeDrawable);
        

        注意:需要材料组件库版本1.1.0

        【讨论】:

        • 这是我的观察,希望能对某人有所帮助。如果你为上面设置了错误的半径(过高,比如 56 而不是 20,例如如果控制高度为 40),上面的角无论如何都会显示正确,但仅限于 api 21。对于 api 19,它们会非常混乱up :) 除非您输入正确的半径。
        【解决方案7】:

        我认为更好的方法是合并两件事:

        1. 制作布局的位图,如图here

        2. 从位图制作一个圆角drawable,如图here

        3. 在 imageView 上设置可绘制对象。

        这将处理其他解决方案未能解决的情况,例如内容有角。

        我认为它对 GPU 更友好,因为它显示的是单层而不是 2。

        唯一更好的方法是制作一个完全自定义的视图,但这需要很多代码并且可能需要很长时间。我认为我在这里提出的建议是两全其美。

        这里有一个关于如何做到的sn-p:

        RoundedCornersDrawable.java

        /**
         * shows a bitmap as if it had rounded corners. based on :
         * http://rahulswackyworld.blogspot.co.il/2013/04/android-drawables-with-rounded_7.html
         * easy alternative from support library: RoundedBitmapDrawableFactory.create( ...) ; 
         */
        public class RoundedCornersDrawable extends BitmapDrawable {
        
            private final BitmapShader bitmapShader;
            private final Paint p;
            private final RectF rect;
            private final float borderRadius;
        
            public RoundedCornersDrawable(final Resources resources, final Bitmap bitmap, final float borderRadius) {
                super(resources, bitmap);
                bitmapShader = new BitmapShader(getBitmap(), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
                final Bitmap b = getBitmap();
                p = getPaint();
                p.setAntiAlias(true);
                p.setShader(bitmapShader);
                final int w = b.getWidth(), h = b.getHeight();
                rect = new RectF(0, 0, w, h);
                this.borderRadius = borderRadius < 0 ? 0.15f * Math.min(w, h) : borderRadius;
            }
        
            @Override
            public void draw(final Canvas canvas) {
                canvas.drawRoundRect(rect, borderRadius, borderRadius, p);
            }
        }
        

        CustomView.java

        public class CustomView extends ImageView {
            private View mMainContainer;
            private boolean mIsDirty=false;
        
            // TODO for each change of views/content, set mIsDirty to true and call invalidate
        
            @Override
            protected void onDraw(final Canvas canvas) {
                if (mIsDirty) {
                    mIsDirty = false;
                    drawContent();
                    return;
                }
                super.onDraw(canvas);
            }
        
            /**
             * draws the view's content to a bitmap. code based on :
             * http://nadavfima.com/android-snippet-inflate-a-layout-draw-to-a-bitmap/
             */
            public static Bitmap drawToBitmap(final View viewToDrawFrom, final int width, final int height) {
                // Create a new bitmap and a new canvas using that bitmap
                final Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                final Canvas canvas = new Canvas(bmp);
                viewToDrawFrom.setDrawingCacheEnabled(true);
                // Supply measurements
                viewToDrawFrom.measure(MeasureSpec.makeMeasureSpec(canvas.getWidth(), MeasureSpec.EXACTLY),
                        MeasureSpec.makeMeasureSpec(canvas.getHeight(), MeasureSpec.EXACTLY));
                // Apply the measures so the layout would resize before drawing.
                viewToDrawFrom.layout(0, 0, viewToDrawFrom.getMeasuredWidth(), viewToDrawFrom.getMeasuredHeight());
                // and now the bmp object will actually contain the requested layout
                canvas.drawBitmap(viewToDrawFrom.getDrawingCache(), 0, 0, new Paint());
                return bmp;
            }
        
            private void drawContent() {
                if (getMeasuredWidth() <= 0 || getMeasuredHeight() <= 0)
                    return;
                final Bitmap bitmap = drawToBitmap(mMainContainer, getMeasuredWidth(), getMeasuredHeight());
                final RoundedCornersDrawable drawable = new RoundedCornersDrawable(getResources(), bitmap, 15);
                setImageDrawable(drawable);
            }
        
        }
        

        编辑:找到了一个不错的替代方案,基于 "RoundKornersLayouts" library。有一个类将用于您希望扩展的所有布局类,并进行四舍五入:

        //based on https://github.com/JcMinarro/RoundKornerLayouts
        class CanvasRounder(cornerRadius: Float, cornerStrokeColor: Int = 0, cornerStrokeWidth: Float = 0F) {
            private val path = android.graphics.Path()
            private lateinit var rectF: RectF
            private var strokePaint: Paint?
            var cornerRadius: Float = cornerRadius
                set(value) {
                    field = value
                    resetPath()
                }
        
            init {
                if (cornerStrokeWidth <= 0)
                    strokePaint = null
                else {
                    strokePaint = Paint()
                    strokePaint!!.style = Paint.Style.STROKE
                    strokePaint!!.isAntiAlias = true
                    strokePaint!!.color = cornerStrokeColor
                    strokePaint!!.strokeWidth = cornerStrokeWidth
                }
            }
        
            fun round(canvas: Canvas, drawFunction: (Canvas) -> Unit) {
                val save = canvas.save()
                canvas.clipPath(path)
                drawFunction(canvas)
                if (strokePaint != null)
                    canvas.drawRoundRect(rectF, cornerRadius, cornerRadius, strokePaint)
                canvas.restoreToCount(save)
            }
        
            fun updateSize(currentWidth: Int, currentHeight: Int) {
                rectF = android.graphics.RectF(0f, 0f, currentWidth.toFloat(), currentHeight.toFloat())
                resetPath()
            }
        
            private fun resetPath() {
                path.reset()
                path.addRoundRect(rectF, cornerRadius, cornerRadius, Path.Direction.CW)
                path.close()
            }
        
        }
        

        然后,在您自定义的每个布局类中,添加与此类似的代码:

        class RoundedConstraintLayout : ConstraintLayout {
            private lateinit var canvasRounder: CanvasRounder
        
            constructor(context: Context) : super(context) {
                init(context, null, 0)
            }
        
            constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
                init(context, attrs, 0)
            }
        
            constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
                init(context, attrs, defStyle)
            }
        
            private fun init(context: Context, attrs: AttributeSet?, defStyle: Int) {
                val array = context.obtainStyledAttributes(attrs, R.styleable.RoundedCornersView, 0, 0)
                val cornerRadius = array.getDimension(R.styleable.RoundedCornersView_corner_radius, 0f)
                val cornerStrokeColor = array.getColor(R.styleable.RoundedCornersView_corner_stroke_color, 0)
                val cornerStrokeWidth = array.getDimension(R.styleable.RoundedCornersView_corner_stroke_width, 0f)
                array.recycle()
                canvasRounder = CanvasRounder(cornerRadius,cornerStrokeColor,cornerStrokeWidth)
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
                    setLayerType(FrameLayout.LAYER_TYPE_SOFTWARE, null)
                }
            }
        
            override fun onSizeChanged(currentWidth: Int, currentHeight: Int, oldWidth: Int, oldheight: Int) {
                super.onSizeChanged(currentWidth, currentHeight, oldWidth, oldheight)
                canvasRounder.updateSize(currentWidth, currentHeight)
            }
        
            override fun draw(canvas: Canvas) = canvasRounder.round(canvas) { super.draw(canvas) }
        
            override fun dispatchDraw(canvas: Canvas) = canvasRounder.round(canvas) { super.dispatchDraw(canvas) }
        
        }
        

        如果您希望支持属性,请按照库中的说明使用:

        <resources>
          <declare-styleable name="RoundedCornersView">
              <attr name="corner_radius" format="dimension"/>
              <attr name="corner_stroke_width" format="dimension"/>
              <attr name="corner_stroke_color" format="color"/>
          </declare-styleable>
        </resources>
        

        另一种选择,对于大多数用途来说可能更容易:使用 MaterialCardView 。它允许自定义圆角、笔触颜色和宽度以及高度。

        例子:

        <FrameLayout
            xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
            android:layout_height="match_parent" android:clipChildren="false" android:clipToPadding="false"
            tools:context=".MainActivity">
        
            <com.google.android.material.card.MaterialCardView
                android:layout_width="100dp" android:layout_height="100dp" android:layout_gravity="center"
                app:cardCornerRadius="8dp" app:cardElevation="8dp" app:strokeColor="#f00" app:strokeWidth="2dp">
        
                <ImageView
                    android:layout_width="match_parent" android:layout_height="match_parent" android:background="#0f0"/>
        
            </com.google.android.material.card.MaterialCardView>
        
        </FrameLayout>
        

        结果:

        请注意,如果您使用它,笔画边缘会出现轻微的伪影问题(在那里会留下一些内容像素)。放大看就知道了。这个问题我已经反馈here了。

        编辑:似乎是固定的,但不是在 IDE 上。举报here

        【讨论】:

        • 感谢您收集这个很棒的答案,它让我朝着正确的方向前进,但我可以在stackoverflow.com/questions/25877515/…stackoverflow.com/questions/25877515/… 上为一个非常相关的问题提供帮助
        • 这会产生错误,因为 ImageView 中没有可用的默认构造函数。
        • 这应该是被接受的答案。而不是平面逻辑,你去寻找一个很棒的解决方案。这也解决了您在 cmets 中提到的其他答案的问题。感谢您的努力,也许您可​​以纠正一个功能齐全的类并通过 github 分享。我认为它可能会帮助太多人。
        • @Senhor 你认为我应该这样做吗?我会考虑的。现在,您可以在此处查看我创建的其他存储库:github.com/AndroidDeveloperLB?tab=repositories
        • 大部分都完成了,你可以试一试。顺便说一句,autofittextview 看起来真的很酷。
        【解决方案8】:

        在drawable中创建你的xml,layout_background.xml

         <?xml version="1.0" encoding="utf-8"?>
            <shape xmlns:android="http://schemas.android.com/apk/res/android" >
              <solid android:color="@color/your_colour" />
              <stroke
                    android:width="2dp"
                    android:color="@color/your_colour" />
              <corners android:radius="10dp" />      
            </shape>
         <--width, color, radius should be as per your requirement-->
        

        然后,将其添加到您的 layout.xml

         android:background="@drawable/layout_background"
        

        【讨论】:

          【解决方案9】:

          如果你想让你的布局变得圆润,最好使用 CardView,它提供了许多使设计美观的功能。

          <android.support.v7.widget.CardView
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              card_view:cardCornerRadius="5dp">
                <LinearLayout
                      android:layout_width="match_parent"
                      android:layout_height="wrap_content">
          
                      <TextView
                          android:layout_width="0dp"
                          android:layout_height="wrap_content"
                          android:layout_weight=".3"
                          android:text="@string/quote_code"
                          android:textColor="@color/white"
                          android:textSize="@dimen/text_head_size" />
                </LinearLayout>
          </android.support.v7.widget.CardView>
          

          使用此 card_view:cardCornerRadius="5dp",您可以更改半径。

          【讨论】:

            【解决方案10】:

            我已将 @gauravsapiens 的答案与我的 cmets 放在一起,让您合理理解这些参数会产生什么影响。

            <?xml version="1.0" encoding="utf-8"?>
            <shape xmlns:android="http://schemas.android.com/apk/res/android">
            
                <!-- Background color -->
                <solid android:color="@color/white" />
            
                <!-- Stroke around the background, width and color -->
                <stroke android:width="4dp" android:color="@color/drop_shadow"/>
            
                <!-- The corners of the shape -->
                <corners android:radius="4dp"/>
            
                <!-- Padding for the background, e.g the Text inside a TextView will be 
                located differently -->
                <padding android:left="10dp" android:right="10dp" 
                         android:bottom="10dp" android:top="10dp" />
            
            </shape>
            

            如果您只是想创建一个圆角的形状,删除填充和描边就可以了。如果您同时移除实体,您实际上会在透明背景上创建圆角。

            为了懒惰,我在下面创建了一个形状,它只是一个带有圆角的纯白色背景 - 享受吧! :)

            <?xml version="1.0" encoding="utf-8"?>
            <shape xmlns:android="http://schemas.android.com/apk/res/android">
            
                <!-- Background color -->
                <solid android:color="@color/white" />
            
                <!-- The corners of the shape -->
                <corners android:radius="4dp"/>
            
            </shape>
            

            【讨论】:

              【解决方案11】:

              以编程方式设置圆角半径的功能

              static void setCornerRadius(GradientDrawable drawable, float topLeft,
                      float topRight, float bottomRight, float bottomLeft) {
                  drawable.setCornerRadii(new float[] { topLeft, topLeft, topRight, topRight,
                          bottomRight, bottomRight, bottomLeft, bottomLeft });
              }
              
              static void setCornerRadius(GradientDrawable drawable, float radius) {
                  drawable.setCornerRadius(radius);
              }
              

              使用

              GradientDrawable gradientDrawable = new GradientDrawable();
              gradientDrawable.setColor(Color.GREEN);
              setCornerRadius(gradientDrawable, 20f);
              //or setCornerRadius(gradientDrawable, 20f, 40f, 60f, 80f); 
              
              view.setBackground(gradientDrawable);
              

              【讨论】:

                【解决方案12】:
                 <shape xmlns:android="http://schemas.android.com/apk/res/android"
                android:padding="@dimen/_10sdp"
                android:shape="rectangle">
                
                <solid android:color="@color/header" />
                
                <corners
                    android:bottomLeftRadius="@dimen/_5sdp"
                    android:bottomRightRadius="@dimen/_5sdp"
                    android:topLeftRadius="@dimen/_5sdp"
                    android:topRightRadius="@dimen/_5sdp" />
                

                【讨论】:

                  【解决方案13】:

                  1:在drawables中定义layout_bg.xml

                  <?xml version="1.0" encoding="UTF-8"?>
                  <shape xmlns:android="http://schemas.android.com/apk/res/android">
                      <solid android:color="#FFFFFF"/>
                      <stroke android:width="3dp" android:color="#B1BCBE" />
                      <corners android:radius="10dp"/>
                      <padding android:left="0dp" android:top="0dp" android:right="0dp" android:bottom="0dp" />
                  </shape>
                  

                  2:将layout_bg.xml 添加为布局的背景

                  android:background="@drawable/layout_bg"
                  

                  【讨论】:

                  • 这不起作用。正如您设置的那样,它是背景,因此内容会覆盖圆角,如果您有内容绘制在角上,您将不会看到它们被圆角。
                  • 几乎总是,我的内容永远不会覆盖角落。这非常有效。
                  • 如何避免错误Element shape doesn't have the required attribute android:layout_height
                  • Element shape doesn't have the required attribute android:layout_height 显示错误的原因是 layout_bg.xml 不在可绘制文件夹中。
                  • @nhouser9:实际上它更像是“它可以工作,但要注意你的前景/内容可能会出现在角落里”。因此,根据用例,它可能 100% 有效。我很高兴答案没有那么多反对票,因为它很有用,我很高兴评论有一百个赞成票,因为很容易发现这个解决方案的局限性。两全其美。
                  【解决方案14】:

                  更好的方法是:

                  background_activity.xml

                  <?xml version="1.0" encoding="UTF-8"?>
                  <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
                      <item android:gravity="fill">
                          <color android:color="@color/black"/>
                      </item>
                      <item>
                          <shape android:gravity="fill">
                              <solid android:color="@color/white"/>
                              <corners android:radius="10dip"/>
                              <padding android:left="0dip" android:top="0dip" android:right="0dip" android:bottom="0dip" />
                          </shape>
                      </item>
                  </layer-list>
                  

                  这也适用于 API 21,并为您提供如下内容:


                  如果您愿意付出更多努力更好地控制,然后使用android.support.v7.widget.CardView 及其cardCornerRadius 属性(并将elevation 属性设置为0dp 以消除与cardView 伴随的任何阴影)。此外,这将在 API 级别低至 15 时起作用。

                  【讨论】:

                  • 如果内容适合背景,它将覆盖它。它并没有真正剪辑到您设置的形状。
                  • 你的意思是另一种观点?您能否更新代码以显示您的意思?这个想法是圆角不会放置黑色区域。四角应该有透明色。
                  • 哦,我现在明白你的问题了。我想为此,您可以在内容上使用一个小的固定边距
                  • 但是,内容不会被剪切成您选择的形状,因为固定边距是矩形的,而不是根据您选择的形状。
                  【解决方案15】:

                  使用 CardView 为任何布局获取圆角边缘。 对 cardview 使用 card_view:cardCornerRadius="5dp" 以获得圆润的布局边缘。

                  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    xmlns:card_view="http://schemas.android.com/apk/res-auto"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical">
                  
                        <android.support.v7.widget.CardView
                          android:layout_width="match_parent"
                          android:layout_height="wrap_content"
                          card_view:cardCornerRadius="5dp">
                            <LinearLayout
                                  android:layout_width="match_parent"
                                  android:layout_height="wrap_content"
                                  android:orientation="horizontal"
                                  android:padding="15dp"
                                  android:weightSum="1">
                  
                                  <TextView
                                      android:layout_width="0dp"
                                      android:layout_height="wrap_content"
                                      android:layout_weight=".3"
                                      android:text="@string/quote_code"
                                      android:textColor="@color/white"
                                      android:textSize="@dimen/text_head_size" />
                  
                                  <TextView
                                      android:layout_width="0dp"
                                      android:layout_height="wrap_content"
                                      android:layout_weight=".7"
                                      android:text="@string/quote_details"
                                      android:textColor="@color/white"
                                      android:textSize="@dimen/text_head_size" />
                              </LinearLayout>
                         </android.support.v7.widget.CardView>
                     </LinearLayout>
                  

                  【讨论】:

                  • support.v7 库中的 CardView,您可以使用 API7 或更高版本。
                  【解决方案16】:

                  我是这样做的:

                  查看截图:

                  drawable文件夹中创建以custom_rectangle.xml命名的drawable文件:

                  <?xml version="1.0" encoding="utf-8"?>
                  <shape xmlns:android="http://schemas.android.com/apk/res/android"
                      android:shape="rectangle" >
                  
                      <solid android:color="@android:color/white" />
                  
                      <corners android:radius="10dip" />
                  
                      <stroke
                          android:width="1dp"
                          android:color="@android:color/white" />
                  
                  </shape>
                  

                  现在在视图上应用矩形背景

                  mView.setBackground(R.drawlable.custom_rectangle);
                  

                  完成

                  【讨论】:

                  • 这不起作用。正如您设置的那样,它是背景,因此内容会覆盖圆角,如果您有内容绘制在角上,您将不会看到它们被圆角。
                  【解决方案17】:

                  这是一个 XML 文件的副本,用于创建具有白色背景、黑色边框和圆角的可绘制对象:

                   <?xml version="1.0" encoding="UTF-8"?> 
                      <shape xmlns:android="http://schemas.android.com/apk/res/android"> 
                          <solid android:color="#ffffffff"/>    
                  
                          <stroke android:width="3dp"
                                  android:color="#ff000000"
                                  />
                  
                          <padding android:left="1dp"
                                   android:top="1dp"
                                   android:right="1dp"
                                   android:bottom="1dp"
                                   /> 
                  
                          <corners android:bottomRightRadius="7dp" android:bottomLeftRadius="7dp" 
                           android:topLeftRadius="7dp" android:topRightRadius="7dp"/> 
                      </shape>
                  

                  将其保存为可绘制目录中的xml文件, 像使用任何可绘制背景(图标或资源文件)一样使用它,使用其资源名称 (R.drawable.your_xml_name)

                  【讨论】:

                  • 喜欢圆角的可能性
                  • 这个答案几乎就是上面的答案。这里唯一真正的变化是每个拐角半径的定义,并且给定每个拐角的相同值,我会将其写在一行中:&lt;corners android:radius="7dp" /&gt; :)
                  • 这对我来说是最好的答案,因为它涵盖了圆角的可用性......干得好,100% 工作
                  • ImageView 的角不圆(剪裁),我该如何解决?
                  【解决方案18】:

                  在 android v7 支持库中使用 CardView。 虽然它有点重,但它解决了所有问题,而且很容易。 不像 set drawable background 方法,它可以成功裁剪子视图。

                  <?xml version="1.0" encoding="utf-8"?>
                  <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
                      xmlns:card_view="http://schemas.android.com/apk/res-auto"
                      xmlns:tools="http://schemas.android.com/tools"
                      android:layout_width="match_parent"
                      android:layout_height="wrap_content"
                      card_view:cardBackgroundColor="@android:color/transparent"
                      card_view:cardCornerRadius="5dp"
                      card_view:cardElevation="0dp"
                      card_view:contentPadding="0dp">
                      <YOUR_LINEARLAYOUT_HERE>
                  </android.support.v7.widget.CardView>
                  

                  【讨论】:

                  • 对于能够“负担得起”它的每个人来说都比其他任何东西都好。让我感到困惑的是,这样一个基本的东西并不是标准 Android 视图的一部分,它是几乎所有 Web 浏览器的 CSS 的主要内容
                  【解决方案19】:

                  最好和最简单的方法是在布局中使用 card_background 可绘制对象。这也遵循 Google 的材料设计指南。只需将其包含在您的 LinearLayout 中即可:

                  android:background="@drawable/card_background"
                  

                  将此添加到您的可绘制目录中并将其命名为card_background.xml

                  <?xml version="1.0" encoding="utf-8"?>
                  <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
                  
                      <item>
                          <shape android:shape="rectangle">
                              <solid android:color="#BDBDBD"/>
                              <corners android:radius="5dp"/>
                          </shape>
                      </item>
                  
                      <item
                          android:left="0dp"
                          android:right="0dp"
                          android:top="0dp"
                          android:bottom="2dp">
                          <shape android:shape="rectangle">
                              <solid android:color="#ffffff"/>
                              <corners android:radius="5dp"/>
                          </shape>
                      </item>
                  </layer-list>
                  

                  【讨论】:

                    【解决方案20】:

                    试试这个...

                    1.创建可绘制的xml(custom_layout.xml):

                    <?xml version="1.0" encoding="utf-8"?>
                    <shape xmlns:android="http://schemas.android.com/apk/res/android" >
                    
                    <solid android:color="#FFFFFF" />
                    
                    <stroke
                        android:width="2dp"
                        android:color="#FF785C" />
                    
                    <corners android:radius="10dp" />
                    
                    </shape>
                    

                    2.添加视图背景

                    android:background="@drawable/custom_layout"
                    

                    【讨论】:

                    • 正如我上面写的类似解决方案:这不起作用。正如您设置的那样,它是背景,因此内容会覆盖圆角,如果您有内容绘制在角上,您将不会看到它们被圆角。
                    【解决方案21】:
                    <?xml version="1.0" encoding="UTF-8"?>
                    <shape xmlns:android="http://schemas.android.com/apk/res/android">
                        <solid android:color="#FFFFFF"/>
                        <stroke android:width="3dip" android:color="#B1BCBE" />
                        <corners android:radius="10dip"/>
                        <padding android:left="3dip" android:top="3dip" android:right="3dip" android:bottom="3dip" />
                    </shape>
                    

                    @David,只要把 padding 的值和 stroke 一样,这样边框就可以看到,不管图片大小

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 2017-10-21
                      • 2019-12-07
                      • 2011-01-28
                      • 2011-10-29
                      • 1970-01-01
                      • 2014-01-25
                      • 1970-01-01
                      • 2017-07-17
                      相关资源
                      最近更新 更多