Android布局组件中实现圆角边框的两种方法

  • 设置corners_bg.xml


设置边框圆角可以在drawable-mdpi目录里定义一个xml: 

[html]  view plain copy
  1. xml version="1.0" encoding="utf-8"?>    
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android">      
  3.     <solid android:color="#FFFFFF" />      
  4.     <corners android:topLeftRadius="10dp"     
  5.              android:topRightRadius="10dp"      
  6.              android:bottomRightRadius="10dp"     
  7.              android:bottomLeftRadius="10dp"/>      
  8. shape>   
解释:

solid的表示填充颜色,为了简单,这里用的是白色。 

而corners则是表示圆角,注意的是这里bottomRightRadius是左下角而不是右下角,bottomLeftRadius右下角。 


上面的效果也可以像下面一样设置,如下:

[html]  view plain copy
  1. <corners android:radius="5dp" />    


引用corners_bg.xml

如果想引用这个xml,只需要@drawable/corners_bg.xml即可: 

[html]  view plain copy
  1. android:background="@drawable/corners_bg"   

  • Java代码动态加载
    /**
     * 代码动态绘制View的圆角边框
     * @param radius 15dp
     * @param borderLength 1dp
     * @param borderColor
     * @return
     */
    public static ShapeDrawable createRoundCornerShapeDrawable(float radius, float borderLength, int borderColor) {
        float[] outerRadii = new float[8];
        float[] innerRadii = new float[8];
        for (int i = 0; i < 8; i++) {
            outerRadii[i] = radius + borderLength;
            innerRadii[i] = radius;
        }

        ShapeDrawable sd = new ShapeDrawable(new RoundRectShape(outerRadii, new RectF(borderLength, borderLength,
                borderLength, borderLength), innerRadii));
        sd.getPaint().setColor(borderColor);

        return sd;
    }

引用createRoundCornerShapeDrawable

          tagTextView.setBackground(createRoundCornerShapeDrawable(
                    radius, (float)DisplayUtils.pxToDip(mContext,BORDER_WIDTH_VALUE),
                    tag_bg_colors[i % (MAX_NUM_OF_SELECTED_TAG_DEFAULT -1)]
                    ));



你可能感兴趣的:(android移动开发)