自定义shape 渐变色

 

<shape xmlns:android="http://schemas.android.com/apk/res/android">

<!--圆角-->
<corners android:radius="60dp"/>

<!--边框-->
<stroke android:color="#EEC177" android:width="1dp"/>

<!--渐变色-->
<gradient
        android:startColor="@android:color/white"
        android:centerColor="@android:color/black"
        android:endColor="@android:color/black"
       />

</shape>

 

### Android Shape Drawable 渐变色 示例 在Android中,`<shape>`标签可以用于定义Drawable资源,并支持渐变色的设置。以下是一个完整的示例,展示如何使用XML定义一个带有渐变色Shape Drawable。 #### XML定义渐变色 可以在`res/drawable`目录下创建一个XML文件来定义渐变色。例如: ```xml <!-- res/drawable/gradient_shape.xml --> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 渐变效果 --> <gradient android:startColor="#FF5722" <!-- 渐变开始颜色 --> android:endColor="#FFC107" <!-- 渐变结束颜色 --> android:angle="270" /> <!-- 渐变角度 --> <!-- 圆角 --> <corners android:radius="16dp" /> <!-- 圆角半径 --> <!-- 描边 --> <stroke android:width="2dp" android:color="#dcdcdc" /> <!-- 描边颜色和宽度 --> <!-- 内边距 --> <padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp" /> </shape> ``` #### 在布局中应用 定义好Drawable后,可以直接将其作为背景应用于任何控件,例如`Button`或`TextView`: ```xml <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/gradient_shape" android:text="渐变色示例" android:padding="16dp" android:textColor="#FFFFFF" /> ``` #### 动态设置渐变色 如果需要在代码中动态设置渐变色,可以使用`GradientDrawable`类。以下是一个示例: ```java GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setColors(new int[]{Color.parseColor("#FF5722"), Color.parseColor("#FFC107")}); // 设置渐变颜色 gradientDrawable.setOrientation(GradientDrawable.Orientation.TOP_BOTTOM); // 设置渐变方向 gradientDrawable.setCornerRadius(16f); // 设置圆角半径 // 将Drawable设置为View的背景 View myView = findViewById(R.id.my_view); myView.setBackground(gradientDrawable); ``` 以上代码展示了如何通过Java代码动态创建一个带有渐变色的Drawable[^2]。 #### 注意事项 - `android:angle`属性值必须是45的倍数(如0、45、90等),并且以水平线为基准,顺时针计算[^1]。 - 如果需要更复杂的渐变效果(如径向渐变或扫描渐变),可以考虑使用自定义View并重写`onDraw()`方法[^3]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值