GradientDrawable动态改变Shape文件
16lz
2021-01-26
1.Shape文件的简单使用
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <size android:width="100dp" android:height="100dp" /> <gradient android:angle="45" android:endColor="#ffffff" android:gradientRadius="50dp" android:startColor="#000000" android:type="linear" /> <solid android:color="#ffffff" /> <corners android:radius="5dp" /> <stroke android:width="2dp" android:color="#22ccdd" android:dashGap="1dp" android:dashWidth="1dp" />shape>
引用的话直接在view的布局文件里android:background="@drawable/test_bg"
引用即可。
2.代码动态改变shape文件
使用GradientDrawable
类可以动态创建shape文件和修改已创建的静态xml文件。
2.1 动态创建shape文件
GradientDrawable gradientDrawable = new GradientDrawable();gradientDrawable.setColor(Color.parseColor("#cccccc"));gradientDrawable.setStroke(1,Color.parseColor("#ffffff"));// GradientDrawable的各种属性myView.setBackground(gradientDrawable);
2.2动态修改已创建的xml文件
GradientDrawable gradientDrawable =(GradientDrawable)myView.getBackground();gradientDrawable.setColor(Color.parseColor("#cccccc"));// gradientDrawable.set 各种属性myView.setBackground(gradientDrawable);
3.例子:渐变背景改变动画
背景图片,左下到右上渐变,起始和终止颜色是(#000000,#ffffff)
黑色到白色,动画变为(#ffffff,#000000)
白色到黑色。
代码:
public static void gradientChange(int startColor1, int startColor2, int endColor1, int endColor2, final View view,final long duration) { final int[] gradientColor = new int[2]; //设置窗口颜色渐变动画 ValueAnimator animator = ValueAnimator.ofInt(startColor1, startColor2); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { gradientColor[0] = (int) animation.getAnimatedValue(); } }); animator.setDuration(duration); animator.setEvaluator(new ArgbEvaluator()); animator.start(); ValueAnimator animator2 = ValueAnimator.ofInt(endColor1, endColor2); animator2.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { gradientColor[1] = (int) animation.getAnimatedValue(); view.setBackground(changeGradientColor(gradientColor[0], gradientColor[1])); } }); animator2.setDuration(duration); animator2.setEvaluator(new ArgbEvaluator()); animator2.start();}//渐变色设置shapeprivate static GradientDrawable changeGradientColor(int startColor, int endColor) { int colors[] = {startColor, endColor};//分别为开始颜色,结束颜色 GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.BL_TR, colors); gradientDrawable.setGradientType(GradientDrawable.LINEAR_GRADIENT); return gradientDrawable;}
更多相关文章
- android 换肤
- Android(安卓)重新编译资源文件
- android studio使用svn时忽略文件列表
- Android(安卓)详解build.gradle文件
- Android(安卓)GreenDao 3.0使用实例讲解
- Android系统定制之源码完美下载
- Ubuntu 下 Android(安卓)反编译 apk
- libxxx.so- text relocations问题的终极解决方案
- keystore文件转换格式为pk8+x509.pem