I'm working on a code, which should make lines. You can touch the screen on two diffrent places, the program gets the x/y values and draws a line. So that's working fine! I want the program now to save the lines. So you can touch the screen multiple times and the program makes a line from the first to the second touch, from the third to the fourth and so on, and displays them all. I tried to do this with an arraylist, but it still didn't worked. Here is the code, which draws the lines, but doesn't sve them.
So the code works now! I made it with Paths and it's working fine! Thank for your help!
package com.example.linienmachen;
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.view.MotionEvent;
import android.view.View;
public class Touchclass extends View {
private Paint paint = new Paint();
private Path path = new Path();
int count = 1;
public Touchclass(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setStrokeWidth(6f);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
@Override
protected void onDraw(Canvas canvas) {
if ((count%2 != 0)){
canvas.drawPath(path, paint);}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
count++;
if(count%2 != 1){
path.moveTo(eventX, eventY);
return true;
}
if(count%2 != 0){
path.lineTo(eventX, eventY);
break;
}
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
// nothing to do
break;
default:
return false;
}
// Schedules a repaint.
invalidate();
return true;
}
}
There's two ways to do this.
1)Store the location of each line, and redraw each line in every onDraw call.
2)Use a bitmap. Every time a new line is created, draw the line directly to the bitmap. Then your onDraw function just draws this bitmap to the screen.
Method 2 uses more memory but has better performance. Method 1 doesn't scale to hundreds of lines, but it takes a lot less memory.