我需要在画布上绘制一个矩形,其中包含来自 ontouch 事件的点。我得到了矩形形状,但是当我绘制另一个矩形时,前一个矩形消失了。我想我需要将矩形点存储在某个数组中。请给我一些想法。
到目前为止,我的代码如下。
首先在视图类的ontouch方法中
private void onTouchEvent(MotionEvent event) {
xTouchCoordinate = event.getX();
yTouchCoordinate = event.getY();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
isActionUp = false;
pushState ();
startX = event.getX();
startY = event.getY();
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
isActionUp = true;
}
else if (event.getAction() == MotionEvent.ACTION_MOVE){
isActionUp = false;
if(mTouchMode == TouchModes.RECTANGLE )
{
updateRectPath(startX,startY , xTouchCoordinate , yTouchCoordinate);
}
}
}
而 onDraw 方法是
protected void onDraw(Canvas canvas) {
ImageObject.setInteractiveMode(true);
int sc = canvas.save();
canvas.drawColor(Color.BLACK);
canvas.scale(mCanvasScale, mCanvasScale);
canvas.translate(mCanvasOffset.x, mCanvasOffset.y);
canvas.clipRect(mCanvasLimits);
canvas.drawColor(Color.WHITE);
if (currentState.drawGrid)
drawGridLines (canvas);
drawImages (canvas, true);
drawLines (canvas);
drawRectangles(canvas);
drawCircles(canvas);
drawOvals(canvas);
drawImages (canvas, false);
}
绘制矩形方法
private void drawRectangles(Canvas canvas) {
try
{
if(path!=null)
{
if(mTouchMode == TouchModes.RECTANGLE)
{
finishPath(canvas);
}
}
}catch(Exception e)
{
}
}
完成路径方法
void finishPath(Canvas canvas) {
if(mTouchMode == TouchModes.RECTANGLE)
{
paint = new Paint();
paint.setAntiAlias(true);
paint.setDither(true);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(currentState.currentColor);
paint.setFlags(Paint.DITHER_FLAG | Paint.ANTI_ALIAS_FLAG);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeWidth(currentStrokeWidth);
canvas.drawPath(path, paint);
}
}
void updateRectPath(float x1, float y1, float x2, float y2) {
path.rewind();
x1 = x1 - mCanvasOffset.x;
y1 = y1 - mCanvasOffset.y;
x2 = x2 - mCanvasOffset.x;
y2 = y2 - mCanvasOffset.y;
translate(x1, y1);
Log.d ("x1 is "+x1, "y1 is "+y1);
if (x1 < x2 && y1 > y2) {
path.addRect(x1, y2, x2, y1, Path.Direction.CW);
}
if (x1 < x2 && y1 < y2) {
path.addRect(x1, y1, x2, y2, Path.Direction.CW);
}
if (x1 > x2 && y1 > y2) {
path.addRect(x2, y2, x1, y1, Path.Direction.CW);
}
if (x1 > x2 && y1 < y2) {
path.addRect(x2, y1, x1, y2, Path.Direction.CW);
}
}