2014-11-08 76 views
0

我想画一条直线,沿着我的手指触摸画布,这样ACTION_DOWN点是起点,ACTION_UP是终点。手指的路径可以是任何东西,但最终数字应该是从起点到终点的一条线。请帮助我使用onDraw()函数。绘图 - Android编程

+0

保持代码的一次... – 2014-11-08 05:45:54

+0

看看Android范例,在您的SDK目录中有一个“FingerPaint”,它处理您的要求 – rupps 2014-11-08 05:57:01

回答

0

,当你从一个点触摸手指到另一个 这是 DrawLineView.java此代码拉绳

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 DrawLineView extends View { 

private Paint paint = new Paint(); 
private Path path= new Path(); 
float eventx; 
float eventy; 

public DrawLineView(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    paint.setAntiAlias(true); 
    paint.setStrokeWidth(5f); 
    paint.setColor(Color.BLUE); 
    paint.setStyle(Paint.Style.STROKE); 
} 
@Override 
protected void onDraw(Canvas canvas) { 
    canvas.drawPath(path, paint); 

} 

@Override 
public boolean onTouchEvent(MotionEvent event) { 
    eventx=event.getX(); 
    eventy=event.getY(); 


    switch(event.getAction()){ 
    case MotionEvent.ACTION_DOWN : 
     path.moveTo(eventx, eventy); 

     return true; 
    case MotionEvent.ACTION_UP : 
     path.lineTo(eventx, eventy); 

     break; 
     default : 
      return false; 

    } 
    invalidate(); 

    return true; 
} 

} 

活动启动它:

import android.app.Activity; 
import android.os.Bundle; 

public class DrawActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(new DrawLineView(this, null)); 
} 


} 
+0

谢谢。但是通过这段代码,我看不到线条,直到我从屏幕上抬起手指。如果可以看到手指后面的线条,那将会很好。 – user4229427 2014-11-08 17:38:13