我几乎是Android开发的新手。 我尝试根据触摸事件绘制线条。它适用于滚动视图。但是,当我使用scrollView时,它只是不起作用。我在其他帖子中读到了一些问题和答案,但没有什么能让我理解代码应该如何。
这是我的代码:
public class CustomDrawingView extends View
{
private final int paintColor = Color.BLACK;
private Paint drawPaint;
private Path path = new Path();
private boolean clearCanvas = false;
public CustomDrawingView(Context context, AttributeSet attrs)
{
super (context, attrs);
setupPaint();
}
private void setupPaint() {
drawPaint = new Paint();
drawPaint.setColor(paintColor);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(5);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float touchX = event.getX();
float touchY = event.getY();
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
path.moveTo(touchX, touchY);
break;
case MotionEvent.ACTION_MOVE:
path.lineTo(touchX, touchY);
break;
}
postInvalidate();
return true;
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, drawPaint);
}
public void clearScreen()
{
path.reset();
postInvalidate();
}
}
MainActifity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mirana.touchinteraction.MainActivity">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.example.mirana.touchinteraction.CustomDrawingView
android:id="@+id/simpleDrawingView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</ScrollView>
</RelativeLayout>
如何根据触摸交互在屏幕上绘制线条?请帮帮我。
在下图中,屏幕包含“工作绘制”是我想要运行的代码(从xml中删除scrollView)。当我将scrollview添加到xml时,就像上面的代码一样,空白屏幕就是结果。我可以通过触摸绘制任何东西并将指针拖到屏幕上。