在Android中,绘制单点触控运动路径可以通过以下步骤实现:
以下是一个简单的示例代码:
public class SinglePointPathView extends ViewGroup {
private Path mPath;
private Paint mPaint;
private Canvas mCanvas;
private Bitmap mBitmap;
public SinglePointPathView(Context context) {
super(context);
init();
}
public SinglePointPathView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public SinglePointPathView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPath = new Path();
mPaint = new Paint();
mPaint.setColor(Color.BLACK);
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(10);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
@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);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
float x = event.getX();
float y = event.getY();
switch (action) {
case MotionEvent.ACTION_DOWN:
mPath.moveTo(x, y);
break;
case MotionEvent.ACTION_MOVE:
mPath.lineTo(x, y);
break;
case MotionEvent.ACTION_UP:
break;
}
mCanvas.drawPath(mPath, mPaint);
invalidate();
return true;
}
}
在Activity中使用:
public class MainActivity extends AppCompatActivity {
private SinglePointPathView mPathView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPathView = new SinglePointPathView(this);
mPathView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
((ViewGroup) findViewById(android.R.id.content)).addView(mPathView);
}
}
这样就可以在Android中绘制单点触控运动路径了。
领取专属 10元无门槛券
手把手带您无忧上云