我想制作一个应用程序,当我触摸屏幕上的某个点并拖动到另一个位置时,会在 ACTION_UP 上绘制一条线,然后从 ACTION_UP 位置绘制另一条线到其他点,依此类推。但是我们有这条线之前绘制的不应在绘制新线时消失。
问问题
1530 次
1 回答
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;
}
}
于 2013-04-11T08:59:52.020 回答