0
我需要製作一個按鈕,它可以清潔我的畫布和一個安全按鈕。 我希望活動保持現狀。道路上所畫的將被刪除。非常感謝您的幫助。我的代碼:畫布上的重置按鈕
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();
}
};
}
你的意思像這樣:public void clear(Canvas canva){Canvas.drawColor(Color.WHI){ TE); } – Veni
@Veni是的。但是,您沒有要傳入的canvas參數。我認爲這是由於使用了「View」而不是「SurfaceView」。所以你可能需要重寫你的代碼。我有另一個想法,使用路徑。讓我編輯我的答案。 – Doomsknight
嗯奇怪,它對我很好 – Veni