美文网首页
Android知识回顾

Android知识回顾

作者: wanTag | 来源:发表于2019-03-29 15:32 被阅读0次

    在项目中会用到颜色渐变,我们通过XML实现

    创建xml文件

    在drawable文件夹下创建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] 很好理解,渐变开始的颜色和渐变结束时的颜色(从什么颜色变到什么颜色)
    
    自定义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>
    

    相关文章

      网友评论

          本文标题:Android知识回顾

          本文链接:https://www.haomeiwen.com/subject/evulbqtx.html