Android知識回顧

在項目中會用到顏色漸變,我們通過XML實現(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] 根標簽,聲明一個shape 
[gradient] 聲明該shape的屬性-漸變色,除此外還有其他屬性如corners、stroke、size等等 
[android:angle]漸變色的角度,舉例來說,0代表從上至下顏色漸變;45代表從左至右顏色漸變;90代表從下至上顏色漸變… 
[android:startColor&android:endColor] 很好理解,漸變開始的顏色和漸變結(jié)束時的顏色(從什么顏色變到什么顏色)
自定義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>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容