Hey I want to draw a line in different patterns by using canvas.
Any idea or suggestion are appreciate ..!!!!
Thanks in advance.
You have to use Path
.Docs say:
The Path class encapsulates compound (multiple contour) geometric paths consisting of straight line segments, quadratic curves, and cubic curves. ...
For example,you can extend a view
and add touch event positions to a path
in onTouchEvent(MotionEvent event)
method of your view.Then you have to generate random positions correspond to newest touch event and add their to other instances of path.Finally in onDraw()
method of your view,draw all paths.I hope this snippet help you to understand my idea:
public class NetCanvas extends View {
private static final double MAX_DIFF = 15;
Path path0 = new Path();
Path path = new Path();
private Paint p0;
private Paint p;
public NetCanvas(Context context) {
super(context);
p0 = new Paint();
p0.setShader(new LinearGradient(0, 0, 230, getHeight(), Color.GREEN,
Color.RED, Shader.TileMode.CLAMP));
p0.setStyle(Style.STROKE);
p = new Paint();
p.setShader(new LinearGradient(0, 0, 230, getHeight(), Color.BLUE,
Color.MAGENTA, Shader.TileMode.CLAMP));
p.setStyle(Style.STROKE);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x0 = event.getX();
float y0 = event.getY();
float x = generateFloat(event.getX());
float y = generateFloat(event.getY());
if (event.getAction() == MotionEvent.ACTION_DOWN) {
path0.moveTo(x0, y0);
path0.lineTo(x0, y0);
path.moveTo(x, y);
path.lineTo(x, y);
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
path0.lineTo(x0, y0);
path.lineTo(x, y);
} else if (event.getAction() == MotionEvent.ACTION_UP) {
path0.lineTo(x0, y0);
path.lineTo(x, y);
}
invalidate();
return true;
}
@Override
public void onDraw(Canvas canvas) {
canvas.drawPath(path0, p0);
canvas.drawPath(path, p);
}
private float generateFloat(Float f){
double d = (Math.signum(2*Math.random() - 1)) * Math.random() * MAX_DIFF;
return (float) (f + d);
}
}
In above code,I used two path
s,but you can use three or more.Also the result,depends on your finger rate on the screen.For example:
or it may looks like this:
Edit:
Above class(NetCanvas
) extends View
,so you can create an instance of it and use that instance,like other views.For example,you can simply set an instance of it as ContentView
of your Activity.Here I override onCreate()
method of Activity:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new NetCanvas(this));
}
Although you can change NetCanvas
to extend SurfaceView
with some other changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With