首页 分享 Android Drawable之GradientDrawable

Android Drawable之GradientDrawable

来源:花匠小妙招 时间:2024-12-21 06:32

GradientDrawable是什么

GradientDrawable在Android中便是shape标签的代码实现,利用GradientDrawable也可以创建出各种形状。

GradientDrawable使用方法

1. 获取控件的shape并进行动态修改:
既然GradientDrawable是shape的动态实现,那么他就可以通过动态的获取控件的shape获取实例并进行修改

布局文件

<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:orientation="vertical" android:gravity="center_horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:text="Change" android:id="@+id/bt" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <View android:id="@+id/view" android:background="@drawable/shape_rect" android:layout_width="300dp" android:layout_height="300dp" /> </LinearLayout>

shape_rect.xml

<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="@color/colorAccent"/> </shape>

2.Java代码修改

默认样式为 shape_rect.xml 指定的矩形

GradientDrawable background = new GradientDrawable(); background.setColor(Color.GREEN); view.setBackground(background);

GradientDrawable.OVAL:椭圆形

GradientDrawable background = new GradientDrawable(); background.setColor(Color.BLUE); background.setShape(GradientDrawable.OVAL); view.setBackground(background);

GradientDrawable.LINE:一条线

GradientDrawable background = new GradientDrawable(); background.setStroke(5,Color.YELLOW); background.setShape(GradientDrawable.LINE); view.setBackground(background);

虚线

GradientDrawable background = new GradientDrawable(); background.setShape(GradientDrawable.LINE); background.setStroke(5,Color.BLACK,10,10);;//第一个参数为线的宽度 第二个参数是线的颜色 第三个参数是虚线段的长度 第四个参数是虚线段之间的间距长度 view.setBackground(background);

GradientDrawable.RING:环形(能力不足画不出来)

颜色渐变

GradientDrawable background = new GradientDrawable(); background.setShape(GradientDrawable.OVAL); background.setStroke(10,Color.DKGRAY);//设置宽度为10px的DKGRAY描边 background.setGradientType(GradientDrawable.LINEAR_GRADIENT);//设置线性渐变,除此之外还有:GradientDrawable.SWEEP_GRADIENT(扫描式渐变),GradientDrawable.RADIAL_GRADIENT(圆形渐变) background.setOrientation(GradientDrawable.Orientation.RIGHT_LEFT);//设置渐变方向 background.setColors(new int[]{Color.RED,Color.BLUE});//增加渐变效果需要使用setColors方法来设置颜色(中间可以增加多个颜色值) background.setAlpha(70);//设置透明度 view.setBackground(background);

参考博客

相关知识

Android研究院之应用程序界面五大布局(九)
Android Studio 实战演练—小猴子摘桃
Android UI之ImageView图片视图
基于Android Studio如何实现 购物商城 案例(简单易上手)
Android移动开发
基于TensorFlow2.3.0的花卉识别Android APP设计
安卓作业
ClassNotFoundException解决方案总结
LinearLayout使一行图标排能自适应屏幕大小,使用layout
Android Studio实现简单的购物商城界面

网址: Android Drawable之GradientDrawable https://www.huajiangbk.com/newsview1212929.html

所属分类:花卉
上一篇: Android编程实战
下一篇: android gone 空白,

推荐分享