Android自定义色盘

好久都没有写自定义了。今天有一个色盘取色的,本来以为会有图片的,结果没有,就只能自定义写了。
这里先看效果图:

Android自定义色盘_第1张图片
色盘.png

分析思路:先画一个大圆,给一个阴影背景;再画一个圆,设置色盘宽度即可。
直接开始写:
初始化:

private Paint mDiskPaint;//色盘画笔
private float mDiskPaintWidth;//色盘宽度
private Shader shader; // 色环颜色的发散位置
private Paint bgPaint;//背景画笔
private float r_bgPaint;//背景圆半径
private float r_shaderPaint;//
//渐变色环颜色
private int[] mCircleColors = new int[] { 0xFFFF0000, 0xFFFF00FF, 0xFF0000FF, 0xFF00FFFF, 0xFF00FF00, 0xFFFFFF00,
        0xFFFF0000 };
  public ColorDiskView(Context context) {
    super(context);
    init();
}

    public ColorDiskView(Context context, AttributeSet attrs) {
    //this(context, attrs,0);
    super(context,attrs);
    init();
}

     public ColorDiskView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

private void init() {
    mDiskPaint=new Paint(Paint.ANTI_ALIAS_FLAG);
    mDiskPaint.setStyle(Paint.Style.STROKE);

    bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    LinearGradient gradient = new LinearGradient(0, 0, 700, 700, 0XFF222222, 0xFF909090, Shader.TileMode.CLAMP);
    bgPaint.setShader(gradient);
}

注意色盘颜色的数组:mCircleColors.
重写onMeasure 方法:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int widthSpecMode=MeasureSpec.getMode(widthMeasureSpec);
    int widthSpecSize=MeasureSpec.getSize(widthMeasureSpec);
    int heightSpecMode=MeasureSpec.getMode(heightMeasureSpec);
    int heightSpecSize=MeasureSpec.getSize(heightMeasureSpec);
    if (widthSpecMode==MeasureSpec.AT_MOST&&heightSpecMode==MeasureSpec.AT_MOST){
        setMeasuredDimension(500,500);
    }else if(widthSpecMode==MeasureSpec.AT_MOST){
            setMeasuredDimension(500,heightSpecSize);
    }else if (heightSpecMode==MeasureSpec.AT_MOST){
            setMeasuredDimension(widthSpecSize,500);
    }
}

最后重写onDraw的方法:

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    final int paddingLeft=getPaddingLeft();
    final int paddingRight=getPaddingRight();
    final int paddingTop=getPaddingTop();
    final int paddingBottom=getPaddingBottom();
    int width=getWidth()-paddingLeft-paddingRight;
    int height=getHeight()-paddingTop-paddingBottom;

    r_bgPaint=Math.min(width,height)/2;
    mDiskPaintWidth=r_bgPaint/12*5;
    r_shaderPaint=r_bgPaint-mDiskPaintWidth/2;

    mDiskPaint.setStrokeWidth(mDiskPaintWidth);

    //圆心确定在填充
    shader=new SweepGradient(paddingLeft+width/2,paddingRight+height/2 ,mCircleColors,null);
    mDiskPaint.setShader(shader);
    canvas.drawCircle(paddingLeft+width/2,paddingRight+height/2,r_bgPaint,bgPaint); //外圆大小
    canvas.drawCircle(paddingLeft+width/2,paddingRight+height/2, r_shaderPaint, mDiskPaint);//色盘大小
}

这样就OK了。其实也很简单的,你也试试。

你可能感兴趣的:(Android自定义色盘)