5

I created a sample drawing app where the user can draw using variable width stroke, So far drawing a path with variable stroke is working, but the lines drawn are not smooth. The code I used to achieve that is shown below.

Help me to sort this out as m stuck on this from the last two days.

Code to draw a path using variable stroke width

public class FingerPaint extends GraphicsActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyView(this));
    }

    public void colorChanged(int color)  {
    }

    public class MyView extends View {

        private static final float STROKE_WIDTH = 5f;    
        private Paint paint = new Paint();
        private Path mPath = new Path();
        ArrayList<Path> mPaths = new ArrayList<Path>();
        ArrayList<Integer> mStrokes = new ArrayList<Integer>();

        private float lastTouchX;
        private float lastTouchY;
        private final RectF dirtyRect = new RectF();
        private int lastStroke = -1;
        int variableWidthDelta = 0;
        
        private static final float STROKE_DELTA = 0.0001f; // for float comparison
        private static final float STROKE_INCREMENT = 0.01f; // amount to interpolate
        private float currentStroke = STROKE_WIDTH;
        private float targetStroke = STROKE_WIDTH;
        
        private float mX, mY;
        private static final float TOUCH_TOLERANCE = 4;

        public MyView(Context context)  {
            super(context);

            paint.setAntiAlias(true);
            paint.setDither(true);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeJoin(Paint.Join.ROUND);
            paint.setStrokeCap(Paint.Cap.ROUND);    
            paint.setStrokeWidth(STROKE_WIDTH);
        }

        public void clear() {
            mPath.reset();
            // Repaints the entire view.
            invalidate();
        }

        @Override
        protected void onDraw(Canvas canvas)  {
            for(int i=0; i<mPaths.size();i++) {
                paint.setStrokeWidth(mStrokes.get(i));
                canvas.drawPath(mPaths.get(i), paint);
            }
        }
    
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            float eventX = event.getX();
            float eventY = event.getY();
            int historySize = event.getHistorySize();

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                    resetDirtyRect(eventX, eventY);
//                  mPath.reset();
                    mPath.moveTo(eventX, eventY);
                    mX = eventX;
                    mY = eventY;
                    break;                  
                }
                case MotionEvent.ACTION_MOVE: {                 
                    if (event.getPressure()>=0.00 && event.getPressure()<0.05) {
                        variableWidthDelta = -2;
                    } else if (event.getPressure()>=0.05 && event.getPressure()<0.10) {
                        variableWidthDelta = -2;
                    } else if (event.getPressure()>=0.10 && event.getPressure()<0.15) {
                        variableWidthDelta = -2;
                    } else if (event.getPressure()>=0.15 && event.getPressure()<0.20) {
                        variableWidthDelta = -2;
                    } else if (event.getPressure()>=0.20 && event.getPressure()<0.25) {
                        variableWidthDelta = -2;
                    } else if (event.getPressure() >= 0.25 && event.getPressure()<0.30) {
                        variableWidthDelta = 1;
                    } else if (event.getPressure() >= 0.30 && event.getPressure()<0.35) {
                        variableWidthDelta = 2;
                    } else if (event.getPressure() >= 0.35 && event.getPressure()<0.40) {
                        variableWidthDelta = 3;
                    } else if (event.getPressure() >= 0.40 && event.getPressure()<0.45) {
                        variableWidthDelta = 4;
                    } else if (event.getPressure() >= 0.45 && event.getPressure()<0.60) {
                        variableWidthDelta = 5;
                    }                                          
                    
                    // if current not roughly equal to target
                    if( Math.abs(targetStroke - currentStroke) > STROKE_DELTA ) 
                    {
                        // move towards target by the increment
                        if( targetStroke > currentStroke)
                        {
                            currentStroke = Math.min(targetStroke, currentStroke + STROKE_INCREMENT);
                        }
                        else
                        {
                            currentStroke = Math.max(targetStroke, currentStroke - STROKE_INCREMENT);
                        }
                       
                    } 
                    mStrokes.add((int) currentStroke);
                    
                    targetStroke = variableWidthDelta;
                    
                    float dx = Math.abs(eventX - mX);
                    float dy = Math.abs(eventY - mY);

                    if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
                        if(lastStroke != variableWidthDelta) {
                            mPath.lineTo(mX, mY);
                            
                            mPath = new Path();
                            mPath.moveTo(mX,mY);
                            mPaths.add(mPath);
                        }
                        
                        mPath.quadTo(mX, mY, (eventX + mX)/2, (eventY + mY)/2);
                        mX = eventX;
                        mY = eventY;
                    }

                    for (int i = 0; i < historySize; i++) {
                        float historicalX = event.getHistoricalX(i);
                        float historicalY = event.getHistoricalY(i);
                        expandDirtyRect(historicalX, historicalY);
                    }
                    break;
                }
                case MotionEvent.ACTION_UP: {
                    for (int i = 0; i < historySize; i++) {
                        float historicalX = event.getHistoricalX(i);
                        float historicalY = event.getHistoricalY(i);
                        expandDirtyRect(historicalX, historicalY);
                    }
                   mPath.lineTo(mX, mY);                   
                   break;
                }
            }
            
            // Include half the stroke width to avoid clipping.
            invalidate();

            lastTouchX = eventX;
            lastTouchY = eventY;
            lastStroke = variableWidthDelta;
            
            return true;
        }
        
        private void expandDirtyRect(float historicalX, float historicalY) {
            if (historicalX < dirtyRect.left) {
                dirtyRect.left = historicalX;
            }  else if (historicalX > dirtyRect.right) {
                dirtyRect.right = historicalX;
            }
            if (historicalY < dirtyRect.top) {
                dirtyRect.top = historicalY;
            } else if (historicalY > dirtyRect.bottom) {
                dirtyRect.bottom = historicalY;
            }
        }

        /**
         * Resets the dirty region when the motion event occurs.
         */
        private void resetDirtyRect(float eventX, float eventY) {
            // The lastTouchX and lastTouchY were set when the ACTION_DOWN
            // motion event occurred.
            dirtyRect.left = Math.min(lastTouchX, eventX);
            dirtyRect.right = Math.max(lastTouchX, eventX);
            dirtyRect.top = Math.min(lastTouchY, eventY);
            dirtyRect.bottom = Math.max(lastTouchY, eventY);
        }
    }
}

Output result that I got

enter image description here

Output that I want to achieve

enter image description here

vvvvv
  • 25,404
  • 19
  • 49
  • 81
AndroidDev
  • 4,521
  • 24
  • 78
  • 126
  • Have you checked FingerPaint demo in APIDemos..?? it has the same functionlaity. and also check this [S-pen SDK](http://developer.samsung.com/s-pen-sdk/sdk/S-Pen-SDK-2-3) – SilentKiller Dec 16 '13 at 12:25
  • @SilentKiller FingerPaint demo doesn't support variable width stroke support, I code this sample app using concept from there only, secondly if i switch to S-penSdk, then my app will run only on samsung devices. – AndroidDev Dec 16 '13 at 12:28
  • no body you can use that SDK for every devices. its not bounded to Samsung devices only. download that API and try it. am sure this will solve your issue. – SilentKiller Dec 16 '13 at 12:30
  • I used it, when i run in other device like HTC, LG etc the app crash and in the logcat it says, That device is not a samsung device. – AndroidDev Dec 16 '13 at 12:33
  • @SilentKiller Ok no problem, So u r creating demo using SpenSdk or Using my code. – AndroidDev Dec 16 '13 at 12:38
  • First will try with your code with help of SpenSdk else S-penSDK. you want sharpness and smoothness in your drawing only which you are not getting – SilentKiller Dec 16 '13 at 12:39
  • Yeh and also variable width stroke changes, Means on light pressure of stylus it will draw a thin line and on high pressure of stylus it will draw a thick line, I think you will know what i mean, and its shown in the screenshot also. – AndroidDev Dec 16 '13 at 12:44

2 Answers2

3

Instead of jumping immediately to a new stroke width when you detect a change, you could set a target and interpolate toward it until you reach it. Your mStrokes would need to be Floats instead of Integers.

private static final float STROKE_DELTA = 0.0001f; // for float comparison
private static final float STROKE_INCREMENT = 0.01f; // amount to interpolate
private float currentStroke = STROKE_WIDTH;
private float targetStroke = STROKE_WIDTH;

Where you currently create a new path for a new stroke width, do something like this:

// if current not roughly equal to target
if( Math.abs(targetStroke - currentStroke) > STROKE_DELTA ) {
    // move towards target by the increment
    if( targetStroke > currentStroke )
        currentStroke = Math.min(targetStroke, currentStroke + STROKE_INCREMENT);
    else
        currentStroke = Math.max(targetStroke, currentStroke - STROKE_INCREMENT);
    mPath.lineTo(mX, mY);

    mPath = new Path();
    mPath.moveTo(mX,mY);
    mPaths.add(mPath);
    mStrokes.add(currentStroke);
}

You would update targetStroke where you currently set variableWidthDelta.

Jake Cobb
  • 1,811
  • 14
  • 27
  • I used your logic and updated the code, Can u please check the way i used your logic is correct or not – AndroidDev Jan 08 '14 at 08:17
  • `mStrokes` needs to be a `List` instead of `List` and remove the `(int)` cast when adding to it. Also don't add to it every time there is move event, your other logic requires the indexes of `mStrokes` and `mPaths` to match and this looks broken now. What happens when you run it? – Jake Cobb Jan 08 '14 at 22:20
  • This http://pastebin.com/RUzBiPMN is the final change which i did in my code, Its fine but not perfect, Can u please check is anything wrong in the code. – AndroidDev Jan 09 '14 at 06:46
  • This are the screen shots https://imageshack.com/i/jjgdd7p https://imageshack.com/i/jwkbgup – AndroidDev Jan 10 '14 at 06:12
  • The code and output look fine to me. Since it looks like you might be targeting handwriting, you might look at [this article about smooth signatures](http://corner.squareup.com/2012/07/smoother-signatures.html) for more advanced ideas. – Jake Cobb Jan 10 '14 at 15:07
  • I looked at their code earlier also, but not able to figure it out, how to used there logic in our code. Do u have some idea on that. – AndroidDev Jan 13 '14 at 10:26
0

Your current code translates pretty much every touch move event (above a certain delta distance) into a new path segment. To make a smooth path, you need to do some processing on this large number of initial points that the user touched, and turn it into a smaller number of quad or cubic path segments.

Have a look at the demo on this page: http://paperjs.org/tutorials/paths/smoothing-simplifying-flattening/#simplifying-paths and the corresponding simplification code: https://github.com/paperjs/paper.js/blob/master/src/path/PathFitter.js

Obviously it's in JavaScript not Java, but you'll need to use a similar algorithm. An added complication will be that you will probably have to break down your smoothed path segments into multiple sub-segments again after smoothing to support varying stroke width within a single segment.

Karsten
  • 310
  • 1
  • 6