Saturday, 3 September 2016

Simple android program using onTouchEvent

This is the MainActivity which calls the TouchToView class,

package com.example.paintouch;

import android.app.Activity;
import android.os.Bundle;


public class MainActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
     //   setContentView(R.layout.activity_main);
        setContentView(new TouchToView(this));
    }

}

Here we have used onTouchEvent which will capture the motion of your finger when touching the screen and also we have defined the Paint and Path with its style, colour and width to get displayed.
The X and Y axis will be mapped with using the paint and path.

package com.example.paintouch;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Join;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.view.MotionEvent;
import android.view.View;

public class TouchToView extends View{
private Paint alphanum = new Paint();
private Path trace = new Path();

public TouchToView(Context context) {
super(context);
// TODO Auto-generated constructor stub
alphanum.setAntiAlias(true);
alphanum.setStrokeWidth(6f);
alphanum.setColor(Color.RED);
alphanum.setStyle(Style.STROKE);
alphanum.setStrokeJoin(Join.ROUND);
}

protected void onDraw(Canvas canvas) {
canvas.drawPath(trace, alphanum);
}

@SuppressLint("ClickableViewAccessibility")
public boolean onTouchEvent(MotionEvent event) {
Float eventX = event.getX();
Float eventY = event.getY();

switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
trace.moveTo(eventX, eventY);
break;
case MotionEvent.ACTION_MOVE:
trace.lineTo(eventX, eventY);
break;
case MotionEvent.ACTION_UP:
// trace.lineTo(eventX, eventY); do nothing
break;
case MotionEvent.ACTION_OUTSIDE:
// trace.lineTo(eventX, eventY); do nothing
break;
default:
return false;
}
invalidate();
return true;

}

}



No comments:

Post a Comment

Expense Handler Application with advance technologies

Budget Planner  One of the application developed with Ionic 4 and Python-Flask.  Ionic 4 code:  https://github.com/logeshbuiltin/Expense...