Android Shape Drawable 静态使用和动态使用(圆角,渐变实现)

Android Shape使用场景:

1. 圆角实现

2. 实现有边框,有填充的背景

3. 实现一个渐变的颜色

一般情况上面三种情况我们会选择android的shape,下面分别介绍shape的静态使用和动态使用

1. shape的静态使用

在drawable中创建一个xml文件,在布局文件中直接引用这个xml文件即可

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <!-- 宽度和高度 -->
    <size
        android:width="50dp"
        android:height="50dp"/>

    <!-- 圆角 -->
    <corners
        android:radius="10dp"/><!-- 设置圆角半径,可以分别设置4个角 -->
    
    <!-- 渐变,这个设置之后一般就不要设置solid填充色了 -->
    <gradient
        android:startColor="@android:color/white"
        android:centerColor="@android:color/black"
        android:endColor="@android:color/black"
        android:useLevel="true"
        android:angle="45"
        android:type="radial"
        android:centerX="0"
        android:centerY="0"
        android:gradientRadius="90"/>
    
    <!-- 间隔 -->
    <padding
        android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp"/>
    
    <!-- 填充 -->
    <solid
        android:color="@android:color/white"/><!-- 填充的颜色 -->
    
    <!-- 描边 -->
    <stroke
        android:width="1dp" <!-- 边框宽度 -->
        android:color="@android:color/black"
        android:dashWidth="1dp"
        android:dashGap="2dp"/>
    
</shape>

 

2. 动态创建shape drawable并使用

View view = null;    // 这个view是你需要设置背景的view
int strokeWidth = 1;     // 1dp 边框宽度
int roundRadius = 5;     // 5dp 圆角半径
int strokeColor = Color.parseColor("#FFFF0000");//边框颜色
int fillColor = Color.parseColor("#FF00FF00"); //内部填充颜色

GradientDrawable gd = new GradientDrawable();//创建drawable
gd.setColor(fillColor);
gd.setCornerRadius(roundRadius);
gd.setStroke(strokeWidth, strokeColor);
view.setBackgroundDrawable(gd);
        
// 创建渐变的shape drawable
int colors[] = { 0xff255779 , 0xff3e7492, 0xffa6c0cd };//分别为开始颜色,中间夜色,结束颜色
GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors);
view.setBackgroundDrawable(gd);

3. 动态改变shape drawable的熟悉

既然shape drawable都能动态创建,那么肯定能过动态修改,我们可以通过先获取view上设置的background drawable

如果是GradientDrawable则强制转换为GradientDrawable,这个时候就可以修改里面的属性,像动态创建时一样设置,设置好之后重新设置给view.

GradientDrawable drawable =(GradientDrawable)view.getBackground();
drawable.setColor(fillColor); // 设置填充色   
drawable.gd.setStroke(strokeWidth, strokeColor); // 设置边框宽度和颜色
gd.setColors(colors);    // 设置渐变颜色数组

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

popfisher

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值