Skip to content

Instantly share code, notes, and snippets.

@tolmachevroman
Created February 6, 2015 19:23
Show Gist options
  • Save tolmachevroman/f122a904254f2d9cb450 to your computer and use it in GitHub Desktop.
Save tolmachevroman/f122a904254f2d9cb450 to your computer and use it in GitHub Desktop.
Drawing view, allows to draw multicolor lines with finger
package com.test.app.widgets;
import java.util.ArrayList;
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.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class DrawPanel extends View {
private Paint paint;
private Path path;
private ColoredPath coloredPath;
private ArrayList<ColoredPath> coloredPaths;
private int lastColor;
public DrawPanel(Context context, AttributeSet attrs) {
super(context, attrs);
lastColor = Color.BLACK;
paint = createPaint();
coloredPaths = new ArrayList<ColoredPath>();
coloredPath = new ColoredPath(new Path(), paint);
coloredPaths.add(coloredPath);
}
@Override
protected void onDraw(Canvas canvas) {
for (ColoredPath p : coloredPaths) {
canvas.drawPath(p.path, p.paint);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
coloredPath.path.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
coloredPath.path.lineTo(eventX, eventY);
break;
case MotionEvent.ACTION_UP:
path = new Path();
coloredPath = new ColoredPath(path, createPaint());
coloredPaths.add(coloredPath);
break;
default:
return false;
}
// Schedules a repaint.
invalidate();
return true;
}
public void setPaintColor(int color) {
coloredPath.paint.setColor(color);
lastColor = color;
}
public void clear() {
coloredPaths.clear();
invalidate();
path = new Path();
coloredPath = new ColoredPath(path, createPaint());
coloredPaths.add(coloredPath);
}
private Paint createPaint() {
Paint temp = new Paint();
temp.setAntiAlias(true);
temp.setStyle(Paint.Style.STROKE);
temp.setStrokeJoin(Paint.Join.ROUND);
temp.setStrokeWidth(6f);
temp.setColor(lastColor);
return temp;
}
}
class ColoredPath {
Paint paint;
Path path;
public ColoredPath(Path path, Paint paint) {
this.path = path;
this.paint = paint;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment