Android 颜色选择器
效果图:
代码:
packagecom.venn.color;
importandroid.content.Context;
importandroid.graphics.Canvas;
importandroid.graphics.Paint;
importandroid.graphics.Point;
importandroid.graphics.RectF;
importandroid.util.AttributeSet;
importandroid.util.Log;
importandroid.view.MotionEvent;
importandroid.view.View;
/**
*@authorVenn
*@Email164942747@qq.com
* */
public classColorControlViewextendsView {
privatePaintmPaint;
privatePaintmControlPaint;
private intmSpace;
private intmSelectColor=0;
privateRectFmRect=newRectF(0,0,0,dpTopx(24));
privateSingleTouchListenermListener;
private int[]mColors=new int[]{0xFFFFFFFF,0xFFC4FF2F,0xFF00B200,0xFF00F3D5,
0xFF00B1F5,0xFF0034C5,0xFF9459FF,0xFFFF9EFF,
0xFFFF6C98,0xFFE84057,0xFFBA0100,0xFFFF6E3F,
0xFFFCFF2C,0xFF999999};
publicColorControlView(Context context) {
this(context, null);
}
publicColorControlView(Context context,AttributeSet attrs) {
this(context,attrs,0);
}
publicColorControlView(Context context,AttributeSet attrs, intdefStyleAttr) {
super(context,attrs,defStyleAttr);
mControlPaint=newPaint();
mPaint=newPaint();
}
public voidsetSingeTouchListener(SingleTouchListener mListener) {
this.mListener= mListener;
}
@Override
public voiddraw(Canvas canvas) {
super.draw(canvas);
mSpace= getWidth() /14;
mPaint.setStrokeWidth(dpTopx(9));
for(inti =0;i
mPaint.setColor(mColors[i]);
canvas.drawLine(mSpace* i,dpTopx(12),mSpace* (i +1),dpTopx(12),mPaint);
}
if(mSelectColor
mRect.left=mSpace*mSelectColor;
mRect.right=mSpace* (mSelectColor==0?1:mSelectColor+1);
mControlPaint.setColor(mColors[mSelectColor]);
canvas.drawRoundRect(mRect,7,7,mControlPaint);
Log.d("selecter",mSelectColor+"");
}
}
@Override
public booleanonTouchEvent(MotionEvent event) {
intx =0;
inty =0;
switch(event.getAction()) {
caseMotionEvent.ACTION_UP:
if(mListener!=null&&mSelectColor
mListener.onChangeColor(mColors[mSelectColor]);
}
break;
caseMotionEvent.ACTION_DOWN:
floatlocation = event.getX() /mSpace;
intselectColor = location <1?0: (int) location;
if(mSelectColor!= selectColor) {
mSelectColor= selectColor;
postInvalidate();
}
break;
caseMotionEvent.ACTION_MOVE:
floatmoveLocation = event.getX() /mSpace;
intselectMoveColor = moveLocation <1?0: (int) moveLocation;
if(selectMoveColor
mSelectColor= selectMoveColor;
postInvalidate();
}
break;
default:
break;
}
return true;
}
@Override
protected voidonMeasure(intwidthMeasureSpec, intheightMeasureSpec) {
super.onMeasure(widthMeasureSpec,heightMeasureSpec);
}
public interfaceSingleTouchListener {
public voidonChangeColor(intcolor);
}
private intdpTopx(floatdp){
returnDensityUtils.dp2px(getContext(),dp);
}
}