---
title: "android  自定义组件圆形边框"
author: "泽.."
date: "2014-11-29T10:47:06Z"
tags: []
categories: ["移动开发"]
slug: "android"
draft: false
lastmod: "2014-11-29T10:47:06Z"
id: 2161759
url: "https://dzc.iteye.com/blog/2161759"
---

在android开发中，我们经常要自定义组件如TextView等背景或边框为四角圆形。

首先，我们在drawable目录下新建一个xml文件，bg.xml

&lt;?xml version="1.0" encoding="utf-8"?&gt;  
&lt;shape xmlns:android="[http://schemas.android.com/apk/res/android](http://schemas.android.com/apk/res/android)"  
    android:shape="rectangle"&gt;&lt;!-- android:shape="" 表示是圆角矩形还是椭圆等等 --&gt;  
    &lt;!-- 背景颜色 --&gt;  
    &lt;solid android:color="@color/mycolor" /&gt;

 

    &lt;!-- padding 表示内部空间距离背景图片内部边距 的距离 --&gt;  
    &lt;padding android:top="15dp" android:bottom="15dp" /&gt;

 

    &lt;!-- 图片边框属性 --&gt;  
    &lt;stroke  
        android:width="0dp"  
        android:color="#ffffff" /&gt;

    &lt;!-- 圆角的程度 --&gt;  
    &lt;corners android:radius="5dp" /&gt;

&lt;!-- 定义背景的渐变  如果是不渐变可不写--&gt;

    &lt;gradient  
        android:angle="45" &lt;!---angle表示方向角度。当angle=0时，渐变色是从左向右。 然后逆时针方向转，当angle=90时为从下往上。-&gt;  
        android:centerColor="@color/center"&lt;!--渐变色的中间颜色--&gt;  
        android:centerX="0.5" &lt;!--渐变的中间   0.5为x轴方向的中间--&gt;  
        android:centerY="0.5"  
        android:endColor="@color/endcolor  
        android:startColor="@color/startcolor"  
        android:type="linear" /&gt;

               &lt;!--  linear 线性渐变，这是默认设置

                 radial 放射性渐变，以开始色为中心。

                 sweep 扫描线式的渐变。--&gt;

&lt;/shape&gt;

 

这样，一个四角圆形的背景就完成了，只需要在view中设置android:background="@drawable/bg"

就可以了。

关于设置按下时背景的改变，请参考另一篇文章[http://dzc.iteye.com/blog/2161737](/blog/2161737)