Android 绘图学习
1GradientDrawable 简介
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
<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);