我试过这样画多条线:
`
l1 = new Path();
l2 = new Path();
l3 = new Path();
l4 = new Path();`
---
`mPathList.add(l1...l4);`
---
`public void onDraw(Canvas canvas) {
...
for (Path path : mPathList) {
canvas.drawPath(path, mOverlayPaint);
}
...
}`
---
`case MotionEvent.ACTION_MOVE:
int X = (int)me.getRawX();
int Y = (int)me.getRawY();
l1.moveTo(X, Y);
l2.moveTo(X + 5, Y);
l3.moveTo(X + 10, Y);
l4.moveTo(X + 15, Y);
break;`
但当我试图画一些东西时,fps会慢慢降低。有什么办法让它工作得好吗?
对不起,我的英语不好
最佳答案
您需要做的是将行存储在ArrayList中,然后读取ArrayList onDraw()。请为视图类尝试以下代码:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
class Line {
float startX, startY, stopX, stopY,
float joinX, joinY = 0;
public Line(float startX, float startY, float stopX, float stopY) {
this.startX = startX;
this.startY = startY;
this.stopX = stopX;
this.stopY = stopY;
}
public Line(float startX, float startY) { // for convenience
this(startX, startY, startX, startY);
}
}
public class DrawView extends View {
Paint paint = new Paint();
ArrayList<Line> lines = new ArrayList<Line>();
public DrawView(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setStrokeWidth(6f);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
@Override
protected void onDraw(Canvas canvas) {
for (Line l : lines) {
canvas.drawLine(l.startX, l.startY, l.stopX, l.stopY, paint);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (joinX <= 0 || joinY <= 0) lines.add(new Line(event.getX(), event.getY()));
else lines.add(new Line(joinX, joinY);
return true;
}
else if ((event.getAction() == MotionEvent.ACTION_MOVE) &&
lines.size() > 0) {
Line current = lines.get(lines.size() - 1);
current.stopX = event.getX();
current.stopY = event.getY();
Invalidate();
return true;
}
else if ((event.getAction() == MotionEvent.ACTION_UP) &&
lines.size() > 0 {
Line current = lines.get(lines.size() - 1);
current.stopX = event.getX();
current.stopY = event.getY();
joinX = event.getX();
joinY = event.getY();
Invalidate();
return true;
}
else {
return false;
}
}
}