Reputation:
I have a custom draw view where I draw lines based on my click and move coordinates. This custom view is added to my main acitvity, where I can change the stroke width of the paint object in the custom view. I store the current stroke width in a static class. In the onDraw()-Method I want to redraw the old Pathes with the old stroke width that I can draw with different widths but it is always the current set stroke width.
MainActivity:
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
if (position == 0) {
Memory.setStrokeWidth(10); //Set stroke width in static class
}
if (position == 1) {
Memory.setStrokeWidth(25);
}
if (position == 2) {
Memory.setStrokeWidth(40);
}
}
Custom Draw View:
private Paint paint;
private Path path;
private HashMap<Path, Float> strokeWidthMemory;
@Override
protected void onDraw(Canvas canvas) {
paint.setStrokeWidth(Memory.getStrokeWidth());
canvas.drawPath(path, paint);
strokeWidthMemory.put(path, paint.getStrokeWidth()); //Save drawn path with stroke width in HashMap
//Redraw old lines with stored stroke width
for (Path p : strokeWidthMemory.keySet()) {
paint.setStrokeWidth(strokeWidthMemory.get(p));
canvas.drawPath(p, paint);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// Get the coordinates of the touch event.
float eventX = event.getX();
float eventY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Set a new starting point
path.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
// Connect the points
path.lineTo(eventX, eventY);
break;
default:
return false;
}
// Makes our view repaint and call onDraw
invalidate();
return true;
}
Upvotes: 1
Views: 2727
Reputation: 302
add stroke width in ACTION_MOVE when you are drawing path. If you are adding stroke width in onDraw than every time you call invalidate hash map is updated with current stroke width value
private Paint paint;
private Path path;
private HashMap<Path, Float> strokeWidthMemory;
@Override
protected void onDraw(Canvas canvas) {
paint.setStrokeWidth(Memory.getStrokeWidth());
canvas.drawPath(path, paint);
//Redraw old lines with stored stroke width
for (Path p : strokeWidthMemory.keySet()) {
paint.setStrokeWidth(strokeWidthMemory.get(p));
canvas.drawPath(p, paint);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// Get the coordinates of the touch event.
float eventX = event.getX();
float eventY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Set a new starting point
path.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
// Connect the points
path.lineTo(eventX, eventY);
strokeWidthMemory.put(path, paint.getStrokeWidth()); //Save drawn path with stroke width in HashMap
break;
default:
return false;
}
// Makes our view repaint and call onDraw
invalidate();
return true;
}
Have a look at this answer for reference.
Upvotes: 1