我试图在画布上用多种颜色绘制,初始颜色效果很好,但是当它切换到另一种颜色时,线条是用前一种颜色绘制的,但是后续线条是用正确的颜色绘制的。即一旦我从绿色切换到黑色,我画的下一条线是绿色的,但从那时起它是黑色的。任何帮助表示赞赏。
public class DrawingPanel extends View implements OnTouchListener {
private static final String TAG = "DrawView";
private static final float MINP = 0.25f;
private static final float MAXP = 0.75f;
private Canvas mCanvas;
private Path mPath;
private Paint mPaint;
private Paint bmPaint;
private Paint gmPaint;
private ArrayList<Path> paths = new ArrayList<Path>();
private Map<Path, Integer> colorsMap = new HashMap<Path,Integer>();
private int selectedcolor;
SharedPreferences settings= getSharedPreferences("Macaroni",0);
private String selColr = settings.getString("DrawColor", "");
public DrawingPanel(Context context) {
super(context);
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(6);
mCanvas = new Canvas();
mPath = new Path();
paths.add(mPath);
colorsMap.put(mPath,getColorSel());
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
protected void onDraw(Canvas canvas) {
for (Path p : paths){
int grabColorFromHash =colorsMap.get(p);
mPaint.setColor(grabColorFromHash);
canvas.drawPath(p, mPaint);
}
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private void touch_start(float x, float y) {
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
Log.i("touch_start","touch_start");
}
private void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
Log.i("touch_move","touch_move");
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
mX = x;
mY = y;
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
mPath = new Path();
paths.add(mPath);
colorsMap.put(mPath,getColorSel());
mPaint.setColor(getColorSel());
}
public int getColorSel()
{
selColr = settings.getString("DrawColor", "");
if (selColr.equalsIgnoreCase("Black")){
mPaint.setColor(Color.BLACK);
selectedcolor = mPaint.getColor();
}
if (selColr.equalsIgnoreCase("Red"))
{
mPaint.setColor(Color.RED);
selectedcolor = mPaint.getColor();
}
if (selColr.equalsIgnoreCase("Green"))
{
mPaint.setColor(Color.GREEN);
selectedcolor = mPaint.getColor();
}
return selectedcolor;
}
@Override
public boolean onTouch(View arg0, MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
}