如何在绘图画布中选择和更改颜色

时间:2015-02-09 05:38:40

标签: android canvas

我正在尝试在这里制作绘画笔应用程序我能够通过触摸手指绘制..但我想要的是用户可以选择不同的颜色并绘制它。可以任何人帮我这个吗?

public class MyTouchEventView extends View {

private Paint paint = new Paint();
private Path path = new Path();
private Paint circlePaint = new Paint();
private Path circlePath = new Path();

public Button btnReset;
public LayoutParams params;
private Spinner sp;

public MyTouchEventView(Context context) {
    super(context);

    paint.setAntiAlias(true);
    paint.setColor(Color.GREEN);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeJoin(Paint.Join.ROUND);
    paint.setStrokeWidth(15f);

    circlePaint.setAntiAlias(true);
    circlePaint.setColor(Color.BLUE);
    circlePaint.setStyle(Paint.Style.STROKE);
    circlePaint.setStrokeJoin(Paint.Join.MITER);
    circlePaint.setStrokeWidth(4f);


    sp=new Spinner(context);
    btnReset = new Button(context);
    btnReset.setText("Clear Screen");

    params = new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT);
    btnReset.setLayoutParams(params);

    btnReset.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub

            // resets the screen
            path.reset();

            // Calls the onDraw() method
            postInvalidate();

        }
    });

}

@Override
protected void onDraw(Canvas canvas) {

    canvas.drawPath(path, paint);
    canvas.drawPath(circlePath, circlePaint);
}

@Override
public boolean onTouchEvent(MotionEvent event) {


    float pointX = event.getX();
    float pointY = event.getY();


    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        path.moveTo(pointX, pointY);

        return true;
    case MotionEvent.ACTION_MOVE:
        path.lineTo(pointX, pointY);
        circlePath.reset();


        circlePath.addCircle(pointX, pointY, 30, Path.Direction.CW);

        break;

    case MotionEvent.ACTION_UP:
        circlePath.reset();

        break;
    default:
        return false;
    }

    // Schedules a repaint.
    // Force a view to draw.
    postInvalidate();
    return true;
}
 }

DrawingBrush.java

public class DrawingBrush extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyTouchEventView tv = new MyTouchEventView(this);
        setContentView(tv);
        addContentView(tv.btnReset, tv.params);
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        finish();
    }

}

1 个答案:

答案 0 :(得分:1)

有现成的解决方案可以帮助您。

Example1

Example2

Example3

Example4