Android 动态修改渐变 GradientDrawable

版权声明:本文为博主原创文章,转载希望能注明出处,感谢。 https://blog.csdn.net/u010126792/article/details/85266103

1GradientDrawable 简介

渐变实现
前面的文章 讲解了如何实现渐变类似LinearGradient,SweepGradient是用于Paint的setShader的,可以通过定义xml的shape,内部利用gradient标签,将shape作为view的背景快速实现渐变。但当我们需要动态修改时,就需要用到GradientDrawable,它和xml方式对应,可以快速生成可以作为view背景的渐变drawable。
构造函数:
两种生成方式:

public GradientDrawable()/**
 * Create a new gradient drawable given an orientation and an array
 * of colors for the gradient.
 */
public GradientDrawable(Orientation orientation, @ColorInt int[] colors)

参数说明:
Orientation:渐变方向,我们知道xml方式的渐变的方向的控制主要利用角度, 渐变的方向 默认为0 从做向右 ,90时从下向上 必须为45的整数倍。
Orientation方向定义如下,很简单就不翻译中文了。

public enum Orientation {
    /** draw the gradient from the top to the bottom */
    TOP_BOTTOM,
    /** draw the gradient from the top-right to the bottom-left */
    TR_BL,
    /** draw the gradient from the right to the left */
    RIGHT_LEFT,
    /** draw the gradient from the bottom-right to the top-left */
    BR_TL,
    /** draw the gradient from the bottom to the top */
    BOTTOM_TOP,
    /** draw the gradient from the bottom-left to the top-right */
    BL_TR,
    /** draw the gradient from the left to the right */
    LEFT_RIGHT,
    /** draw the gradient from the top-left to the bottom-right */
    TL_BR,
}

colors:渐变的颜色数组。

2 xml实现渐变

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:angle="0"
        android:endColor="#FFC54E"
        android:startColor="#FF9326"
        android:type="linear" />
    <corners
        android:bottomLeftRadius="25dp"
        android:bottomRightRadius="25dp"
        android:topLeftRadius="25dp"
        android:topRightRadius="25dp" />
</shape>

在这里插入图片描述

3GradientDrawable 实现渐变

**setCornerRadii(): **设置shape的圆角,大小为8(可以大于8),共四对参数,分别表示top-left, top-right, bottom-right, bottom-left的圆角。
setCornerRadius(roundRadius): 设置圆角,四个圆角大小相同。

setColor(fillColor): 设置填充色,此时会使用设置的颜色,而不会使用渐变色
setStroke(strokeWidth, strokeColor): 设置边框宽度和颜色
setGradientType(GradientDrawable.RECTANGLE): 设置渐变形状,包括RECTANT,OVAL,LINE,RING

setGradientCenter(float x, float y): 渐变中心坐标
**setOrientation(GradientDrawable.Orientation orientation):**设置渐变方向,包括从上到下,从左到右,从下到上,从右到左
**setColors(int[] colors):**设置渐变的颜色数组

inflate(Resources r, XmlPullParser parser, AttributeSet attrs, Resources.Theme theme)
从xml文件中加载得到drawable

实例代码:

tv = findViewById(R.id.tv);
int[] colors = {0xFFFF9326,0xFFFFC54E};
GradientDrawable drawable = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT,colors);
drawable.setCornerRadius(25);
drawable.setGradientType(GradientDrawable.RECTANGLE);
tv.setBackground(drawable);

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/u010126792/article/details/85266103
今日推荐