0
我試圖用畫布繪製線條。我能夠畫出一條線,但是一旦我從屏幕上取下手指,它就會消失。我需要線路在屏幕上可見。這是我的代碼`在畫布上繪製後線條消失
public class CanvasView extends View {
private Canvas mcanvas;
private Bitmap mBitmap;
private Path mPath;
private Paint mPaint;
private float mX,mY;
private static final float TOLERANCE = 5;
Context context;
private float firstX ;
private float firstY ;
public CanvasView(Context c, AttributeSet attrs) {
super(c, attrs);
context = c;
mPath = new Path();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeWidth(4f);
firstX = (float)68.85;
firstY = (float)60.25;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mBitmap = Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888);
mcanvas = new Canvas(mBitmap);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// canvas.drawPath(mPath, mPaint);
// canvas.drawPoint(mX,mY,mPaint);/*just a point tarvel
canvas.drawLine(firstX,firstY,mX,mY,mPaint);
}
private void downTouch(float x, float y){
mPath.reset();
mPath.moveTo(x,y);
mX = x;
mY = y;
firstX = x;
firstY = y;
}
private void moveTouch(float x, float y){
// float dx = Math.abs(x - mX);
// float dy = Math.abs(y - mY);
// if (dx >= TOLERANCE || dy >= TOLERANCE) {
// mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
mX = x;
mY = y;
// }
}
private void upTouch(float x, float y){
mPath.lineTo(x,y);
mPath.moveTo(x,y);
firstX = x;
firstY = y;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
downTouch(x,y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
moveTouch(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
upTouch(x,y);
invalidate();
break;
}
return true;
}
public void clearCanvas(){
mPath.reset();
invalidate();
}
}`
任何人都可以幫助我。任何幫助/建議表示讚賞。 在此先感謝。
你需要多條線才能在你的畫布上顯示? –
@SalmanKhakwani是的,我需要根據用戶需要多次繪製線條。 – elsa