Android 颜色选择器之ColorPickerDialog剖析

有这样一个需求,可以让用户自定义背景颜色,这就需要提供一个颜色选择器给用户.在Android 中,如何实现这样的功能呢,遇到这种需求是,先查看一下ApiDemos是否已经有相关的实例,果然,找到了一个可以参考的demo:ColorPickerDialog。我已经把apidemos导入到eclipse中,请看截图:

我们要找的就是这个ColorPickerDialog,在com.example.android.apis.graphics目录下,是一个颜色选择器对话框,在哪个demo中使用的呢,References下之后,发现是在

FingerPaint,也就是涂鸦的例子中:


接下来还是直接看代码:

  1. package com.example.android.apis.graphics;
  2. import android.os.Bundle;
  3. import android.app.Dialog;
  4. import android.content.Context;
  5. import android.graphics.*;
  6. import android.view.MotionEvent;
  7. import android.view.View;
  8. public class ColorPickerDialog extends Dialog {
  9. public interface OnColorChangedListener {
  10. void colorChanged(int color);
  11. }
  12. private OnColorChangedListener mListener;
  13. privateint mInitialColor;
  14. privatestatic class ColorPickerViewextends View {//颜色选择器自定义View
  15. private Paint mPaint;<span><span></span><spanclass="comment">//渐变色环画笔</span><span> </span></span>
  16. private Paint mCenterPaint;<span><span></span><spanclass="comment">//中间圆画笔</span><span> </span></span>
  17. private final int[] mColors;<span><span></span><span class="comment">//渐变色环颜色</span><span></span></span>
  18. private OnColorChangedListener mListener;//颜色改变回调
  19. ColorPickerView(Context c, OnColorChangedListener l,int color) {
  20. super(c);
  21. mListener = l;
  22. mColors = new int[] {//渐变色数组
  23. 0xFFFF0000,0xFFFF00FF, 0xFF0000FF, 0xFF00FFFF, 0xFF00FF00,
  24. 0xFFFFFF00, 0xFFFF0000
  25. };
  26. Shader s = new SweepGradient(0,0, mColors, null);
  27. //初始化渐变色画笔
  28. mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
  29. mPaint.setShader(s);
  30. mPaint.setStyle(Paint.Style.STROKE);
  31. mPaint.setStrokeWidth(32);
  32. //初始化中心园画笔
  33. mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
  34. mCenterPaint.setColor(color);
  35. mCenterPaint.setStrokeWidth(5);
  36. }
  37. privateboolean mTrackingCenter;
  38. private boolean mHighlightCenter;
  39. @Override
  40. protectedvoid onDraw(Canvas canvas) {
  41. float r = CENTER_X - mPaint.getStrokeWidth()*0.5f;
  42. //移动中心
  43. canvas.translate(CENTER_X, CENTER_X);
  44. //画出色环和中心园
  45. canvas.drawOval(new RectF(-r, -r, r, r), mPaint);
  46. canvas.drawCircle(0,0, CENTER_RADIUS, mCenterPaint);
  47. if (mTrackingCenter) {
  48. int c = mCenterPaint.getColor();
  49. mCenterPaint.setStyle(Paint.Style.STROKE);
  50. if (mHighlightCenter) {
  51. mCenterPaint.setAlpha(0xFF);
  52. } else {
  53. mCenterPaint.setAlpha(0x80);
  54. }
  55. canvas.drawCircle(0,0,
  56. CENTER_RADIUS + mCenterPaint.getStrokeWidth(),
  57. mCenterPaint);
  58. mCenterPaint.setStyle(Paint.Style.FILL);
  59. mCenterPaint.setColor(c);
  60. }
  61. }
  62. @Override
  63. protectedvoid onMeasure(int widthMeasureSpec,int heightMeasureSpec) {
  64. setMeasuredDimension(CENTER_X*2, CENTER_Y*2);
  65. }
  66. privatestatic final int CENTER_X = 100;
  67. private static final int CENTER_Y =100;
  68. privatestatic final int CENTER_RADIUS = 32;
  69. privateint floatToByte(float x) {
  70. int n = java.lang.Math.round(x);
  71. return n;
  72. }
  73. privateint pinToByte(int n) {
  74. if (n < 0) {
  75. n = 0;
  76. } else if (n > 255) {
  77. n = 255;
  78. }
  79. return n;
  80. }
  81. private int ave(int s, int d,float p) {
  82. return s + java.lang.Math.round(p * (d - s));
  83. }
  84. private int interpColor(int colors[], float unit) {
  85. if (unit <=0) {
  86. return colors[0];
  87. }
  88. if (unit >= 1) {
  89. return colors[colors.length -1];
  90. }
  91. float p = unit * (colors.length -1);
  92. int i = (int)p;
  93. p -= i;
  94. // now p is just the fractional part [0...1) and i is the index
  95. int c0 = colors[i];
  96. int c1 = colors[i+1];
  97. int a = ave(Color.alpha(c0), Color.alpha(c1), p);
  98. int r = ave(Color.red(c0), Color.red(c1), p);
  99. int g = ave(Color.green(c0), Color.green(c1), p);
  100. int b = ave(Color.blue(c0), Color.blue(c1), p);
  101. return Color.argb(a, r, g, b);
  102. }
  103. privateint rotateColor(int color,float rad) {
  104. float deg = rad * 180 / 3.1415927f;
  105. int r = Color.red(color);
  106. int g = Color.green(color);
  107. int b = Color.blue(color);
  108. ColorMatrix cm = new ColorMatrix();
  109. ColorMatrix tmp = new ColorMatrix();
  110. cm.setRGB2YUV();
  111. tmp.setRotate(0, deg);
  112. cm.postConcat(tmp);
  113. tmp.setYUV2RGB();
  114. cm.postConcat(tmp);
  115. final float[] a = cm.getArray();
  116. int ir = floatToByte(a[0] * r + a[1] * g + a[2] * b);
  117. int ig = floatToByte(a[5] * r + a[6] * g + a[7] * b);
  118. int ib = floatToByte(a[10] * r + a[11] * g + a[12] * b);
  119. return Color.argb(Color.alpha(color), pinToByte(ir),
  120. pinToByte(ig), pinToByte(ib));
  121. }
  122. private static final float PI =3.1415926f;
  123. @Override
  124. public boolean onTouchEvent(MotionEvent event) {
  125. float x = event.getX() - CENTER_X;
  126. float y = event.getY() - CENTER_Y;
  127. boolean inCenter = java.lang.Math.sqrt(x*x + y*y) <= CENTER_RADIUS;
  128. switch (event.getAction()) {
  129. case MotionEvent.ACTION_DOWN:
  130. mTrackingCenter = inCenter;
  131. if (inCenter) {//是否则中心园
  132. mHighlightCenter = true;
  133. invalidate();
  134. break;
  135. }
  136. case MotionEvent.ACTION_MOVE:
  137. if (mTrackingCenter) {
  138. if (mHighlightCenter != inCenter) {
  139. mHighlightCenter = inCenter;
  140. invalidate();
  141. }
  142. } else {
  143. float angle = (float)java.lang.Math.atan2(y, x);
  144. // need to turn angle [-PI ... PI] into unit [0....1]
  145. float unit = angle/(2*PI);
  146. if (unit < 0) {
  147. unit += 1;
  148. }
  149. mCenterPaint.setColor(interpColor(mColors, unit));
  150. invalidate();
  151. }
  152. break;
  153. case MotionEvent.ACTION_UP:
  154. if (mTrackingCenter) {
  155. if (inCenter) {
  156. mListener.colorChanged(mCenterPaint.getColor());
  157. }
  158. mTrackingCenter = false;// so we draw w/o halo
  159. invalidate();
  160. }
  161. break;
  162. }
  163. return true;
  164. }
  165. }
  166. public ColorPickerDialog(Context context,
  167. OnColorChangedListener listener,
  168. int initialColor) {
  169. super(context);
  170. mListener = listener;
  171. mInitialColor = initialColor;
  172. }
  173. @Override
  174. protectedvoid onCreate(Bundle savedInstanceState) {
  175. super.onCreate(savedInstanceState);
  176. OnColorChangedListener l = new OnColorChangedListener() {
  177. public void colorChanged(int color) {
  178. mListener.colorChanged(color);
  179. dismiss();
  180. }
  181. };
  182. setContentView(new ColorPickerView(getContext(), l, mInitialColor));
  183. setTitle("Pick a Color");
  184. }
  185. }
package com.example.android.apis.graphics;

import android.os.Bundle;
import android.app.Dialog;
import android.content.Context;
import android.graphics.*;
import android.view.MotionEvent;
import android.view.View;

public class ColorPickerDialog extends Dialog {

    public interface OnColorChangedListener {
        void colorChanged(int color);
    }

    private OnColorChangedListener mListener;
    private int mInitialColor;

    private static class ColorPickerView extends View {//颜色选择器自定义View
        private Paint mPaint;<span class="comment">//渐变色环画笔</span> 
        private Paint mCenterPaint;<span class="comment">//中间圆画笔</span>  
        private final int[] mColors;<span class="comment">//渐变色环颜色</span>
        private OnColorChangedListener mListener;//颜色改变回调
        
        ColorPickerView(Context c, OnColorChangedListener l, int color) {
            super(c);
            mListener = l;
            mColors = new int[] {//渐变色数组
                0xFFFF0000, 0xFFFF00FF, 0xFF0000FF, 0xFF00FFFF, 0xFF00FF00,
                0xFFFFFF00, 0xFFFF0000
            };
            Shader s = new SweepGradient(0, 0, mColors, null);
            //初始化渐变色画笔
            mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            mPaint.setShader(s);
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setStrokeWidth(32);
            
            //初始化中心园画笔
            mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            mCenterPaint.setColor(color);
            mCenterPaint.setStrokeWidth(5);
        }
        
        private boolean mTrackingCenter;
        private boolean mHighlightCenter;

        @Override 
        protected void onDraw(Canvas canvas) {
            float r = CENTER_X - mPaint.getStrokeWidth()*0.5f;
            
            //移动中心
            canvas.translate(CENTER_X, CENTER_X);
            //画出色环和中心园
            canvas.drawOval(new RectF(-r, -r, r, r), mPaint);            
            canvas.drawCircle(0, 0, CENTER_RADIUS, mCenterPaint);
            
            if (mTrackingCenter) {
                int c = mCenterPaint.getColor();
                mCenterPaint.setStyle(Paint.Style.STROKE);
                
                if (mHighlightCenter) {
                    mCenterPaint.setAlpha(0xFF);
                } else {
                    mCenterPaint.setAlpha(0x80);
                }
                canvas.drawCircle(0, 0,
                                  CENTER_RADIUS + mCenterPaint.getStrokeWidth(),
                                  mCenterPaint);
                
                mCenterPaint.setStyle(Paint.Style.FILL);
                mCenterPaint.setColor(c);
            }
        }
        
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            setMeasuredDimension(CENTER_X*2, CENTER_Y*2);
        }
        
        private static final int CENTER_X = 100;
        private static final int CENTER_Y = 100;
        private static final int CENTER_RADIUS = 32;

        private int floatToByte(float x) {
            int n = java.lang.Math.round(x);
            return n;
        }
        private int pinToByte(int n) {
            if (n < 0) {
                n = 0;
            } else if (n > 255) {
                n = 255;
            }
            return n;
        }
        
        private int ave(int s, int d, float p) {
            return s + java.lang.Math.round(p * (d - s));
        }
        
        private int interpColor(int colors[], float unit) {
            if (unit <= 0) {
                return colors[0];
            }
            if (unit >= 1) {
                return colors[colors.length - 1];
            }
            
            float p = unit * (colors.length - 1);
            int i = (int)p;
            p -= i;

            // now p is just the fractional part [0...1) and i is the index
            int c0 = colors[i];
            int c1 = colors[i+1];
            int a = ave(Color.alpha(c0), Color.alpha(c1), p);
            int r = ave(Color.red(c0), Color.red(c1), p);
            int g = ave(Color.green(c0), Color.green(c1), p);
            int b = ave(Color.blue(c0), Color.blue(c1), p);
            
            return Color.argb(a, r, g, b);
        }
        
        private int rotateColor(int color, float rad) {
            float deg = rad * 180 / 3.1415927f;
            int r = Color.red(color);
            int g = Color.green(color);
            int b = Color.blue(color);
            
            ColorMatrix cm = new ColorMatrix();
            ColorMatrix tmp = new ColorMatrix();

            cm.setRGB2YUV();
            tmp.setRotate(0, deg);
            cm.postConcat(tmp);
            tmp.setYUV2RGB();
            cm.postConcat(tmp);
            
            final float[] a = cm.getArray();

            int ir = floatToByte(a[0] * r +  a[1] * g +  a[2] * b);
            int ig = floatToByte(a[5] * r +  a[6] * g +  a[7] * b);
            int ib = floatToByte(a[10] * r + a[11] * g + a[12] * b);
            
            return Color.argb(Color.alpha(color), pinToByte(ir),
                              pinToByte(ig), pinToByte(ib));
        }
        
        private static final float PI = 3.1415926f;

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            float x = event.getX() - CENTER_X;
            float y = event.getY() - CENTER_Y;
            boolean inCenter = java.lang.Math.sqrt(x*x + y*y) <= CENTER_RADIUS;
            
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    mTrackingCenter = inCenter;
                    if (inCenter) {//是否则中心园
                        mHighlightCenter = true;
                        invalidate();
                        break;
                    }
                case MotionEvent.ACTION_MOVE:
                    if (mTrackingCenter) {
                        if (mHighlightCenter != inCenter) {
                            mHighlightCenter = inCenter;
                            invalidate();
                        }
                    } else {
                        float angle = (float)java.lang.Math.atan2(y, x);
                        // need to turn angle [-PI ... PI] into unit [0....1]
                        float unit = angle/(2*PI);
                        if (unit < 0) {
                            unit += 1;
                        }
                        mCenterPaint.setColor(interpColor(mColors, unit));
                        invalidate();
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    if (mTrackingCenter) {
                        if (inCenter) {
                            mListener.colorChanged(mCenterPaint.getColor());
                        }
                        mTrackingCenter = false;    // so we draw w/o halo
                        invalidate();
                    }
                    break;
            }
            return true;
        }
    }

    public ColorPickerDialog(Context context,
                             OnColorChangedListener listener,
                             int initialColor) {
        super(context);
        
        mListener = listener;
        mInitialColor = initialColor;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        OnColorChangedListener l = new OnColorChangedListener() {
            public void colorChanged(int color) {
                mListener.colorChanged(color);
                dismiss();
            }
        };

        setContentView(new ColorPickerView(getContext(), l, mInitialColor));
        setTitle("Pick a Color");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值