Android中的彩虹型颜色选择器

时间:2010-12-04 07:15:01

标签: android

我是Android新手。我的要求是实现一个颜色选择器,它在彩虹模型中滚动颜色,从我想要选择一种颜色。

1 个答案:

答案 0 :(得分:0)

用于颜色选择器使用API​​ Demos中的ColorPickerDialog类,以及如何在此代码中使用它的描述。所以这是尝试。

package com.SampleCanvas;

import java.util.ArrayList;
import com.SampleCanvas.ColorPickerDialog.OnColorChangedListener;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;

public class SampleCanvasActivity extends Activity implements OnTouchListener,                                     OnClickListener, OnColorChangedListener {

DrawPanel dp;
private ArrayList<Path> pointsToDraw = new ArrayList<Path>();
private Paint mPaint;
Path path;
int color;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    dp = new DrawPanel(this);
    setContentView(R.layout.main);

    dp = new DrawPanel(this); 
    dp.setOnTouchListener(this);

    Button btn=(Button)findViewById(R.id.btnColor);
    btn.setOnClickListener(this);

    mPaint = new Paint();
    mPaint.setColor(Color.WHITE);
    mPaint.setAntiAlias(true);
    mPaint.setDither(true);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeJoin(Paint.Join.ROUND);
    mPaint.setStrokeCap(Paint.Cap.ROUND);
    mPaint.setStrokeWidth(5);
    FrameLayout fl = (FrameLayout)findViewById(R.id.frameLayout);

    fl.addView(dp,LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);  

}


@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    dp.pause();
}
@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    dp.resume();
}

public boolean onTouch(View v, MotionEvent me) {
    // TODO Auto-generated method stub
            synchronized(pointsToDraw)
            {
    if(me.getAction() == MotionEvent.ACTION_DOWN){
        path = new Path();
        path.moveTo(me.getX(), me.getY());
        //path.lineTo(me.getX(), me.getY());
        pointsToDraw.add(path);
    }else if(me.getAction() == MotionEvent.ACTION_MOVE){
        path.lineTo(me.getX(), me.getY());
    }else if(me.getAction() == MotionEvent.ACTION_UP){
        //path.lineTo(me.getX(), me.getY());
    }
    }       
    return true;
}


public class DrawPanel extends SurfaceView implements Runnable{

    Thread t = null;
    SurfaceHolder holder;
    boolean isItOk = false ;

    public DrawPanel(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        holder = getHolder();
    }

    public void run() {
        // TODO Auto-generated method stub
        while( isItOk == true){

            if(!holder.getSurface().isValid()){
                continue;
            }

            Canvas c = holder.lockCanvas();
            c.drawARGB(255, 0, 0, 0);
            onDraw(c);
            holder.unlockCanvasAndPost(c);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        super.onDraw(canvas);
                    synchronized(pointsToDraw)
                    {
        for (Path path : pointsToDraw) {
            canvas.drawPath(path, mPaint);
        }
                    }
    }

    public void pause(){
        isItOk = false;
        while(true){
            try{
                t.join();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            break;
        }
        t = null;
    }

    public void resume(){
        isItOk = true;  
        t = new Thread(this);
        t.start();

    }
}


public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.btnColor:
        new ColorPickerDialog(this, this,mPaint.getColor()).show();
        break;

    default:
        break;
    }
}


public void colorChanged(int color) {
    // TODO Auto-generated method stub
    mPaint.setColor(color);
}
   }

并且拾色器类是

  package com.SampleCanvas;
  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 {
    private Paint mPaint;
    private Paint mCenterPaint;
    private final int[] mColors;
    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");
   }
  }