package com.example.AndroidTest;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import java.util.LinkedList;
公共类CustomView扩展了View {
private final Paint brush;
private LinkedList<Figures> figuras;
public int id;
private float startX;
private float endX;
private float startY;
private float endY;
Figures fig; // á partida é para mudar para o createFigure
public CustomView(Context context, LinkedList <Figures> figures)
{
super(context);
brush = new Paint();
brush.setStyle(Style.STROKE);
brush.setColor(Color.WHITE);
brush.setStrokeWidth(6);
figuras = figures;
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
createFigure( startX, startY, endX, endY);
fig.drawFigure(canvas, brush);
invalidate();
}
public String getString(){
String joined = TextUtils.join("\n\n", figuras); return joined;
} // criar uma string a copiar o conteudo duma list com o intervalo de uma virgula.
@Override
public boolean onTouchEvent( MotionEvent event) {
if (event.getAction() == event.ACTION_DOWN) {
startY = event.getY();
startX = event.getX();
endY = event.getY();
endX = event.getX();
figuras.add(fig);
Toast.makeText(getContext(), "" + figuras.size(), Toast.LENGTH_SHORT).show();
} else if (event.getAction() == event.ACTION_MOVE) {
endY = event.getY();
endX = event.getX();
figuras.getLast().setEndVars(endX, endY);
}
return super.onTouchEvent(event);
}
public void createFigure(float startX, float startY, float endX, float endY) {
switch (id) // aqui crio a figura Fig fig = new line/circle/rect
{
case 0:
fig = new Line(startX, startY, endX, endY);
break;
case 1:
fig = new Circle(startX, startY, endX, endY);
break;
case 2:
fig = new Rectangle(startX, startY, endX, endY);
break;
}
//return fig;
}
public void setID(int aux)
{
id = aux;
}
public LinkedList<Figures> getArray()
{
return figuras;
}
}
答案 0 :(得分:0)
致电invalidate
后,所有已绘制的内容都将被删除,并且会再次调用onDraw。目前,您正在绘制一个无限循环,每次使用startY,startX,endY和endX变量的当前值绘制一个数字,然后使您绘制的内容无效。如果这些变量发生了变化,那么旧的数字将不再被绘制。
为了绘制新图形和所有旧图形,每次调用onDraw时,您必须迭代figuras
并再次绘制每个图形。然后您应该看到所有数字都添加到figuras
,因此您想要绘制所有数字。像这样:
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
for(Figures f : figuras) {
f.drawFigure(canvas, brush);
}
}
另外两个关于表现的概念。您应该在invalidate
中拨打onTouchEvent
,而不是onDraw
。这将节省大量的计算能力。目前我打赌你可以用你的手机作为暖手器。
您还应该在onTouchEvent
中创建图形。在onDraw
只做必要的事情。其他一切都应该在onDraw
之外。