我想创建一个应用程序,当我触摸屏幕上的某个点并拖动到另一个位置时,在ACTION_UP上绘制一条线,然后从ACTION_UP位置绘制另一条线到其他点,依此类推。但是我们之前绘制的线不应该在绘制新线时消失。
答案 0 :(得分:3)
public class LineDrawerView extends View
{
public LineDrawerView(Context context, AttributeSet attrs) {
super(context, attrs);
}
ArrayList<Rect> lines= new ArrayList<Rect>();
int x1, y1;
int x2, y2;
boolean drawing=false;
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
canvas.drawColor(Color.YELLOW);
Paint p= new Paint();
p.setColor(Color.BLACK);
if (drawing)
canvas.drawLine(x1, y1, x2, y2, p);
else
for (int i=0; i<lines.size(); i++)
{
Rect currline= lines.get(i);
canvas.drawLine(currline.left, currline.top, currline.right, currline.bottom, p);
}
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
boolean result=false;
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
x1=x2= (int)event.getX();
y1=y2= (int)event.getY();
drawing=true;
result=true;
break;
case MotionEvent.ACTION_MOVE:
x2= (int)event.getX();
y2= (int)event.getY();
result=true;
break;
case MotionEvent.ACTION_UP:
x2= (int)event.getX();
y2= (int)event.getY();
lines.add(new Rect(x1, y1, x2, y2));
drawing=false;
result=true;
break;
}
if (result) invalidate();
return result;
}
}