Permalink
Browse files

Drawing Paths

  • Loading branch information...
dragosholban committed Apr 20, 2018
1 parent 63b3121 commit acd049c2725ca1927d0b2cf937e36c24548edc78
@@ -0,0 +1,60 @@
package com.dragosholban.androiddrawing;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.view.View;
import java.util.ArrayList;
public class DrawingView extends View {
private ArrayList<Path> paths = new ArrayList<>();
public DrawingView(Context context) {
super(context);
}
public DrawingView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public DrawingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public DrawingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public void addPath(Path path) {
paths.add(path);
}
public Path getLastPath() {
if (paths.size() > 0) {
return paths.get(paths.size() - 1);
}
return null;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (Path path : paths) {
Paint paint = new Paint();
paint.setColor(0X80000000);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3f);
canvas.drawPath(path, paint);
}
}
}
@@ -5,9 +5,14 @@
public class MainActivity extends AppCompatActivity {
DrawingView drawingView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawingView = findViewById(R.id.canvas);
drawingView.setOnTouchListener(new TouchListener());
}
}
@@ -0,0 +1,35 @@
package com.dragosholban.androiddrawing;
import android.graphics.Path;
import android.view.MotionEvent;
import android.view.View;
public class TouchListener implements View.OnTouchListener {
@Override
public boolean onTouch(View view, MotionEvent event) {
float x = event.getX();
float y = event.getY();
DrawingView drawingView = (DrawingView) view;
Path path;
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
path = new Path();
path.moveTo(x, y);
drawingView.addPath(path);
break;
case MotionEvent.ACTION_MOVE:
path = drawingView.getLastPath();
if (path != null) {
path.lineTo(x, y);
}
break;
}
drawingView.invalidate();
return true;
}
}
@@ -6,7 +6,7 @@
android:layout_height="match_parent"
android:background="#AFAFAF"
tools:context=".MainActivity">
<View
<com.dragosholban.androiddrawing.DrawingView
android:id="@+id/canvas"
android:layout_width="0dp"
android:layout_height="0dp"

0 comments on commit acd049c

Please sign in to comment.