自定义属性设置颜色

首先我们需要创建一个文件夹,在res下的values下面创建attr
attr.xml里面的内容及介绍

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!--声明-设置样式:表示一个属性组它的名字必须和你自定义视图的名字相同-->
    <declare-styleable name="Lunpan">
        <!--attr:表示单独的一个属性.format代表属性的格式格式包括很多种:比如颜色,数值,枚举等。-->
        <attr name="title_color" format="color"></attr>
        <attr name="title_color2" format="color"></attr>
        <attr name="title_color3" format="color"></attr>
        <attr name="title_color4" format="color"></attr>
        <attr name="title_color5" format="color"></attr>
        <attr name="title_color6" format="color"></attr>
    </declare-styleable>
</resources>

回到需要写颜色的地方用自己的属性写颜色
在这里插入图片描述
我是使用自定义控件的时候使用的所以我在初始化操作的时候定义使用
color的类型是int

//用于自定义样式,
        mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.Lunpan);
        color = mTypedArray.getColor(R.styleable.Lunpan_title_color, 0);
        color2 = mTypedArray.getColor(R.styleable.Lunpan_title_color2, 0);
        color3 = mTypedArray.getColor(R.styleable.Lunpan_title_color3, 0);
        color4 = mTypedArray.getColor(R.styleable.Lunpan_title_color4, 0);
        color5 = mTypedArray.getColor(R.styleable.Lunpan_title_color5, 0);
        color6 = mTypedArray.getColor(R.styleable.Lunpan_title_color6, 0);

接下来判断使用,绘制6个弧度

if(color != -1){
            mPaint.setColor(color);
            canvas.drawArc(rectF,start * 0,start,true,mPaint);
        }
        if(color2 != -1){
            mPaint.setColor(color2);
            canvas.drawArc(rectF,start * 1,start,true,mPaint);
        }
        if(color3 != -1){
            mPaint.setColor(color3);
            canvas.drawArc(rectF,start * 2,start,true,mPaint);
        }
        if(color4 != -1){
            mPaint.setColor(color4);
            canvas.drawArc(rectF,start * 3,start,true,mPaint);
        }
        if(color5 != -1){
            mPaint.setColor(color5);
            canvas.drawArc(rectF,start * 4,start,true,mPaint);
        }
        if(color6 != -1){
            mPaint.setColor(color6);
            canvas.drawArc(rectF,start * 5,start,true,mPaint);
        }

效果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/jiahui6666/article/details/83898122