ColorPickerView in Android
public class ColorPickerView extends View {
private Paint mPaint;
private int[] mColors;
private OnColorChangedListener mListener;
public ColorPickerView(Context context) {
super(context);
init();
}
public ColorPickerView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ColorPickerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mColors = new int[] {
0xFFFF0000, // red
0xFF00FF00, // green
0xFF0000FF, // blue
0xFFFF00FF, // magenta
0xFFFFFF00, // yellow
0xFF00FFFF // cyan
};
mPaint = new Paint();
mPaint.setStyle(Paint.Style.FILL);
mPaint.setAntiAlias(true);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// set the view dimensions to be a square
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int size = Math.min(width, height);
setMeasuredDimension(size, size);
}
@Override
protected void onDraw(Canvas canvas) {
int width = getWidth();
int height = getHeight();
int colorCount = mColors.length;
float arc = 360f / colorCount;
RectF rectF = new RectF(0, 0, width, height);
for (int i = 0; i < colorCount; i++) {
mPaint.setColor(mColors[i]);
canvas.drawArc(rectF, i * arc, arc, true, mPaint);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
int width = getWidth();
int height = getHeight();
int colorCount = mColors.length;
float arc = 360f / colorCount;
float centerX = width / 2f;
float centerY = height / 2f;
double angle = Math.atan2(y - centerY, x - centerX);
angle = (angle < 0) ? (angle + 2 * Math.PI) : angle;
int index = (int) (angle / arc);
int color = mColors[index];
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
if (mListener != null) {
mListener.onColorChanged(color);
}
break;
case MotionEvent.ACTION_UP:
// do nothing
break;
default:
return false;
}
return true;
}
public void setOnColorChangedListener(OnColorChangedListener listener) {
mListener = listener;
}
public interface OnColorChangedListener {
void onColorChanged(int color);
}
}