我需要制作一个可以清理画布的按钮和一个安全按钮。 我希望活动保持不变。只是路径被绘制的东西将被删除。非常感谢你的任何帮助。我的代码:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class TouchEventDraw extends View {
//Variable
private Paint paint = new Paint();
private Path path = new Path();
//Konstruktor
public TouchEventDraw(Context context, AttributeSet attrset) {
super(context, attrset);
paint.setAntiAlias(true);
paint.setColor(Color.BLACK);
paint.setStrokeJoin(Paint.Join.MITER);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5f);
}
/**
* The most important step in drawing a custom view is to override the
* @param canvas object that the view can use to draw itself. */
@Override
protected void onDraw(Canvas canvas) {
if(path.isEmpty())
canvas.drawColor(Color.WHITE);
else
canvas.drawPath(path, paint);
}
/**
* Method to handle touch screen motion events.
* @param event The motion event
* @return True if the event was handled, false otherwise.*/
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPos = event.getX();
float yPos = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(xPos,yPos);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(xPos,yPos);
break;
case MotionEvent.ACTION_UP:
break;
default:
return false;
}
invalidate();
return true;
}
public void clear(){
path = new Path();
invalidate();
}
}
我的按钮活动:
import android.graphics.Canvas;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class DrawingScreen extends AppCompatActivity {
Button btn;
TouchEventDraw ted;
Canvas canva;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ted=new TouchEventDraw(this,null);
setContentView(R.layout.activity_drawing_screen);
btn=(Button) findViewById(R.id.button);
btn.setOnClickListener(onClickListener);
}
private final View.OnClickListener onClickListener=new View.OnClickListener() {
@Override
public void onClick(View v) {
ted.clear();
ted.invalidate();
}
};
}
答案 0 :(得分:0)
您需要向-m32
课程添加方法,并在其中调用以下内容
TouchEventDraw
然后在按钮上单击,调用您创建的方法。
您应该能够使用我提供的信息实施解决方案。
我认为通过您的代码存在更多致命问题,我看到以下内容:
另一种方法是,您应该能够创建一个方法,而是将canva.drawColor(Color.WHITE);
设置为空
path
然后将你的平局改为
public void clear(){
path = new Path();
}
并致电@Override
protected void onDraw(Canvas canvas) {
if(path.isEmpty())
canvas.drawColor(Color.WHITE);
else
canvas.drawPath(path, paint);
}