在項(xiàng)目中會(huì)用到顏色漸變完残,我們通過XML實(shí)現(xiàn)
創(chuàng)建xml文件
在drawable文件夾下創(chuàng)建shape資源:
shape_gradient.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:angle="90"
android:endColor="@color/colorAccent"
android:startColor="@color/colorPrimary" />
</shape>
注:
[shape] 根標(biāo)簽,聲明一個(gè)shape
[gradient] 聲明該shape的屬性-漸變色,除此外還有其他屬性如corners甲捏、stroke即纲、size等等
[android:angle]漸變色的角度,舉例來說,0代表從上至下顏色漸變歧胁;45代表從左至右顏色漸變;90代表從下至上顏色漸變…
[android:startColor&android:endColor] 很好理解厉碟,漸變開始的顏色和漸變結(jié)束時(shí)的顏色(從什么顏色變到什么顏色)
自定義View
MyView.java
public class MyView extends View {
public MyView(Context context) {
super(context);
}
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//獲取View的寬高
int width = getWidth();
int height = getHeight();
int colorStart = getResources().getColor(R.color.red);
int color1 = Color.GRAY;
int colorEnd = getResources().getColor(R.color.star_yellow);
Paint paint = new Paint();
LinearGradient backGradient = new LinearGradient(0, 0, 0, height, new int[]{colorStart, color1, colorEnd}, null, Shader.TileMode.CLAMP);
paint.setShader(backGradient);
canvas.drawRect(0, 0, width, height, paint);
}
}
使用在xml中:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.yunlin.xihai.user.gradient.view.MyView
android:layout_width="match_parent"
android:layout_height="200dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>