Draw line and generate error when lines collide - android

I'm drawing circle and want that when lines match together then generate error.I have done some coding and this code is able to draw lines on touch but problem is that when line match together its unable to generate error.So can anybody suggest me what i'm doing wrong.
Code
public class DrawView extends View implements View.OnTouchListener {
private static final String TAG = "DrawView";
List<Point> points = new ArrayList<Point>();
Paint paint = new Paint();
public DrawView(Context context) {
super(context);
setFocusable(true);
setFocusableInTouchMode(true);
DrawView.this.setOnTouchListener(DrawView.this);
paint.setColor(Color.WHITE);
paint.setAntiAlias(true);
}
public void onDraw(Canvas canvas) {
for (Point point : points) {
canvas.drawCircle(point.x, point.y, 5, paint);
// canvas.drawLine(point.x, point.y, 5, 0, paint);
// canvas.drawPaint(p);
// Log.d(TAG, "Painting: "+point);
}
}
public boolean onTouch(View view, MotionEvent event) {
// if(event.getAction() != MotionEvent.ACTION_DOWN)
// return super.onTouchEvent(event);
Point point = new Point();
point.x = event.getX();
point.y = event.getY();
for (int i = 0; i < points.size(); i++) {
if (point.equals(points.get(i))) {
System.out
.println("*****************************ERROR*******************************************");
} else {
System.out.println("Value of points" + points);
System.out
.println("***********************ELSE***********************************");
}
}
points.add(point);
invalidate();
Log.d(TAG, "point: " + point);
return true;
}
}
class Point {
float x, y;
public boolean equals(Object o) {
if (!(o instanceof Point))
return false;
Point p = (Point) o;
return x == p.x && y == p.y;
}
public String toString() {
return x + ", " + y;
}
}

You need to implement equals()-method for your Point class. The default implementation probably won't compare your x & y attributes.

Related

Android canvas how to animate a drawn circle

Hi people I'm doing a Conect4 and I want to do that the circle fall since the pixel number 200 for example to the correspondent pixel or row. I did before animations in XML and I know how to animate the canvas but I didn't find a question to translate a circle to make the sensation that is falling.
Sorry if mi english is bad but I'm a 1 of Bachillerato Student of Spain.
I did this onTocuh and onDraw methods :
public class MyView extends View {
public MyView(Context context) {
super(context);
}
public void CaidaFicha () {
ValueAnimator caidaFicha = ObjectAnimator.ofInt(this,"caida",200,1000);
caidaFicha.setDuration(10000);
caidaFicha.setEvaluator(new IntEvaluator());
caidaFicha.setRepeatCount(ValueAnimator.INFINITE);
caidaFicha.setRepeatMode(ValueAnimator.REVERSE);
caidaFicha.start();
}
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
int x = getWidth();
int y = getHeight();
anchoX = x;
anchoY = y;
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.BLUE);
canvas.drawPaint(paint);
/*Texto*/
paint.setColor(Color.BLACK);
paint.setTextSize(80);
canvas.drawText("CONECTA 4", 70, 130, paint);
/*Separador*/
paint.setColor(Color.parseColor("#5C5C5C"));
canvas.drawRect(0, 200, 600, 210, paint);
/*Tablero*/
int radius = 25;
for (int i = 0; i < Game.NFILAS; i++)
for (int j = 0; j < Game.NCOLUMNAS; j++){
if (game.estaVacio(i,j)){
color = Color.WHITE;
paint.setColor(color);
canvas.drawCircle(getPixelFromColumna(j), getPixelFromFila(i), radius, paint);
} else if (game.estaJugador(i,j)){
paint.setColor(coloreado);
canvas.drawCircle(getPixelFromColumna(j), getPixelFromFila(i), radius, paint);
} else {
color = Color.RED;
paint.setColor(color);
canvas.drawCircle(getPixelFromColumna(j),getPixelFromFila(i), radius, paint);
}
}
}
public boolean onTouchEvent(MotionEvent event) {
int fila;
int columna;
int pixel_x;
int pixel_y;
if(event.getAction() == MotionEvent.ACTION_DOWN) {
pixel_x = (int) event.getX();
pixel_y = (int) event.getY();
fila = getFila(pixel_y);
columna = getColumna(pixel_x);
if (game.tableroLleno()) {
Toast.makeText(getApplicationContext(), R.string.fin_del_juego,
Toast.LENGTH_LONG).show();
}
if (game.sePuedeColocarFicha(fila, columna) != true) {
Toast.makeText(getApplicationContext(), R.string.nosepuedecolocarficha,
Toast.LENGTH_SHORT).show();
return false;
}
if(pixel_y > 200){
game.ponerJugador(fila, columna);
if(game.comprobarCuatro(Game.JUGADOR)){
Toast.makeText(getApplicationContext(), "Ha ganado " + nombreFinal,
Toast.LENGTH_LONG).show();
if(game.fin()) {
fragmento_dialogo dialogo = new fragmento_dialogo();
dialogo.show(getFragmentManager(), "Alert Dialog");
}
}
game.juegaMaquina();
if(game.comprobarCuatro(Game.MAQUINA)){
Toast.makeText(getApplicationContext(), "Has perdido " + nombreFinal,
Toast.LENGTH_LONG).show();
if(game.fin()) {
fragmento_dialogo dialogo = new fragmento_dialogo();
dialogo.show(getFragmentManager(), "Alert Dialog");
}
}
}
}
invalidate();
return true;
}
}

Zoom mapview is lost draw line direction

I doing building a appplication direction from this point to that point on map google. My code run success, but when i zoom in map, draw line direction on map is lost. When zoom out map, my line draw appear. Can you help me!
this source code draw line between two point!
class MyOverLay extends Overlay {
private final List<GeoPoint> points;
private boolean drawStartEnd;
private int pathColor;
public MyOverLay(List<GeoPoint> pointToDraw) {
// TODO Auto-generated constructor stub
this(pointToDraw, Color.BLUE, true);
}
public MyOverLay(List<GeoPoint> points, int pathColor,
boolean drawStartEnd) {
this.points = points;
this.pathColor = pathColor;
this.drawStartEnd = drawStartEnd;
}
private void drawOval(Canvas canvas, Paint paint, Point point) {
Paint ovalPaint = new Paint(paint);
ovalPaint.setStyle(Paint.Style.FILL_AND_STROKE);
ovalPaint.setStrokeWidth(3);
ovalPaint.setColor(Color.BLUE);
int _radius = 7;
RectF oval = new RectF(point.x - _radius, point.y - _radius,
point.x + _radius, point.y + _radius);
canvas.drawOval(oval, ovalPaint);
}
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
Projection projection = mapView.getProjection();
if (shadow == false && points != null) {
Point startPoint = null, endPoint = null;
Path path = new Path();
// We are creating the path
for (int i = 0; i < points.size(); i++) {
GeoPoint gPointA = points.get(i);
Point pointA = new Point();
projection.toPixels(gPointA, pointA);
if (i == 0) { // This is the start point
startPoint = pointA;
path.moveTo(pointA.x, pointA.y);
} else {
if (i == points.size() - 1)// This is the end point
endPoint = pointA;
path.lineTo(pointA.x, pointA.y);
}
}
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(pathColor);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(8);
paint.setAlpha(100);
if (getDrawStartEnd()) {
if (startPoint != null) {
drawOval(canvas, paint, startPoint);
}
if (endPoint != null) {
drawOval(canvas, paint, endPoint);
}
}
if (!path.isEmpty())
canvas.drawPath(path, paint);
}
return super.draw(canvas, mapView, shadow, when);
}
public boolean getDrawStartEnd() {
return drawStartEnd;
}
public void setDrawStartEnd(boolean markStartEnd) {
drawStartEnd = markStartEnd;
}
}

Draw line along points using finger

I can actually draw lines with finger in my app using the FingerPaint in API Demos given in samples of Android SDK. But how to draw these lines with finger only along points placed on the screen. I want something like in this app:https://play.google.com/store/apps/details?id=zok.android.dots
I just want to draw line between point 1 and point 2 with finger. The line between 1 and 2 must be drawn only if the point 2 is touched, else it shouldn't be drawn. Likewise, again from point 2 to point 3 and so on.
Please help me with a code for this.
Thanks in advance
P.S. Please have a look at the app in the link well before answering so that you would have a clear idea about my requirement.
Update:
public class PaintView extends View {
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mPaint;
private static final int TOUCH_TOLERANCE_DP = 20;
private static final int BACKGROUND = 0xFFDDDDDD;
private List<Point> mPoints = new ArrayList<Point>();
private int mLastPointIndex = 0;
private int mTouchTolerance;
private boolean isPathStarted = false;
public PaintView(Context context) {
super(context);
mCanvas = new Canvas();
mPath = new Path();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(12);
mTouchTolerance = dp2px(TOUCH_TOLERANCE_DP);
// TODO just test points
Point p1 = new Point(133, 123);
Point p2 = new Point(149, 136);
Point p3 = new Point(182, 136);
Point p4 = new Point(206, 118);
Point p5 = new Point(208, 87);
Point p6 = new Point(187, 71);
Point p7 = new Point(144, 78);
Point p8 = new Point(124, 101);
Point p9 = new Point(113, 128);
Point p10 = new Point(112, 157);
Point p11 = new Point(119, 188);
Point p12 = new Point(134, 209);
Point p13 = new Point(162, 228);
Point p14 = new Point(194, 238);
Point p15 = new Point(232, 240);
Point p16 = new Point(263, 237);
Point p17 = new Point(289, 224);
Point p18 = new Point(315, 204);
Point p19 = new Point(332, 174);
Point p20 = new Point(339, 128);
Point p21 = new Point(329, 95);
Point p22 = new Point(304, 73);
Point p23 = new Point(280, 69);
Point p24 = new Point(254, 87);
Point p25 = new Point(248, 116);
Point p26 = new Point(259, 143);
Point p27 = new Point(278, 153);
Point p28 = new Point(241, 157);
Point p29 = new Point(192, 160);
Point p30 = new Point(150, 159);
mPoints.add(p1);
mPoints.add(p2);
mPoints.add(p3);
mPoints.add(p4);
mPoints.add(p5);
mPoints.add(p6);
mPoints.add(p7);
mPoints.add(p8);
mPoints.add(p9);
mPoints.add(p10);
mPoints.add(p11);
mPoints.add(p12);
mPoints.add(p13);
mPoints.add(p14);
mPoints.add(p15);
mPoints.add(p16);
mPoints.add(p17);
mPoints.add(p18);
mPoints.add(p19);
mPoints.add(p20);
mPoints.add(p21);
mPoints.add(p22);
mPoints.add(p23);
mPoints.add(p24);
mPoints.add(p25);
mPoints.add(p26);
mPoints.add(p27);
mPoints.add(p28);
mPoints.add(p29);
mPoints.add(p30);
}
public PaintView(Context context, AttributeSet attrs) {
super(context, attrs);
mCanvas = new Canvas();
mPath = new Path();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(12);
mTouchTolerance = dp2px(TOUCH_TOLERANCE_DP);
// TODO just test points
Point p1 = new Point(133, 123);
Point p2 = new Point(149, 136);
Point p3 = new Point(182, 136);
Point p4 = new Point(206, 118);
Point p5 = new Point(208, 87);
Point p6 = new Point(187, 71);
Point p7 = new Point(144, 78);
Point p8 = new Point(124, 101);
Point p9 = new Point(113, 128);
Point p10 = new Point(112, 157);
Point p11 = new Point(119, 188);
Point p12 = new Point(134, 209);
Point p13 = new Point(162, 228);
Point p14 = new Point(194, 238);
Point p15 = new Point(232, 240);
Point p16 = new Point(263, 237);
Point p17 = new Point(289, 224);
Point p18 = new Point(315, 204);
Point p19 = new Point(332, 174);
Point p20 = new Point(339, 128);
Point p21 = new Point(329, 95);
Point p22 = new Point(304, 73);
Point p23 = new Point(280, 69);
Point p24 = new Point(254, 87);
Point p25 = new Point(248, 116);
Point p26 = new Point(259, 143);
Point p27 = new Point(278, 153);
Point p28 = new Point(241, 157);
Point p29 = new Point(192, 160);
Point p30 = new Point(150, 159);
mPoints.add(p1);
mPoints.add(p2);
mPoints.add(p3);
mPoints.add(p4);
mPoints.add(p5);
mPoints.add(p6);
mPoints.add(p7);
mPoints.add(p8);
mPoints.add(p9);
mPoints.add(p10);
mPoints.add(p11);
mPoints.add(p12);
mPoints.add(p13);
mPoints.add(p14);
mPoints.add(p15);
mPoints.add(p16);
mPoints.add(p17);
mPoints.add(p18);
mPoints.add(p19);
mPoints.add(p20);
mPoints.add(p21);
mPoints.add(p22);
mPoints.add(p23);
mPoints.add(p24);
mPoints.add(p25);
mPoints.add(p26);
mPoints.add(p27);
mPoints.add(p28);
mPoints.add(p29);
mPoints.add(p30);
}
public PaintView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mCanvas = new Canvas();
mPath = new Path();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(12);
mTouchTolerance = dp2px(TOUCH_TOLERANCE_DP);
}
#Override
protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
super.onSizeChanged(width, height, oldWidth, oldHeight);
clear();
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(BACKGROUND);
canvas.drawBitmap(mBitmap, 0, 0, null);
canvas.drawPath(mPath, mPaint);
// TODO remove if you dont want points to be drawn
for (Point point : mPoints) {
canvas.drawPoint(point.x, point.y, mPaint);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up(x, y);
invalidate();
break;
}
return true;
}
private void touch_start(float x, float y) {
if (checkPoint(x, y, mLastPointIndex)) {
mPath.reset();
// user starts from given point so path can beis started
isPathStarted = true;
} else {
// user starts move from point which doen's belongs to mPinst list
isPathStarted = false;
}
}
//ADDED WITH LAST EDIT
private void touch_move(float x, float y) {
// draw line with finger move
if (isPathStarted) {
mPath.reset();
Point p = mPoints.get(mLastPointIndex);
mPath.moveTo(p.x, p.y);
if (checkPoint(x, y, mLastPointIndex + 1)) {
p = mPoints.get(mLastPointIndex + 1);
mPath.lineTo(p.x, p.y);
mCanvas.drawPath(mPath, mPaint);
mPath.reset();
++mLastPointIndex;
} else {
mPath.lineTo(x, y);
}
}
}
/**
* Draws line.
*/
private void touch_up(float x, float y) {
mPath.reset();
if (checkPoint(x, y, mLastPointIndex + 1) && isPathStarted) {
// move finished at valid point so draw whole line
// start point
Point p = mPoints.get(mLastPointIndex);
mPath.moveTo(p.x, p.y);
// end point
p = mPoints.get(mLastPointIndex + 1);
mPath.lineTo(p.x, p.y);
mCanvas.drawPath(mPath, mPaint);
mPath.reset();
// increment point index
++mLastPointIndex;
isPathStarted = false;
}
}
/**
* Sets paint
*
* #param paint
*/
public void setPaint(Paint paint) {
this.mPaint = paint;
}
/**
* Returns image as bitmap
*
* #return
*/
public Bitmap getBitmap() {
return mBitmap;
}
/**
* Clears canvas
*/
public void clear() {
mBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
mBitmap.eraseColor(BACKGROUND);
mCanvas.setBitmap(mBitmap);
invalidate();
}
/**
* Checks if user touch point with some tolerance
*/
private boolean checkPoint(float x, float y, int pointIndex) {
if (pointIndex == mPoints.size()) {
// out of bounds
return false;
}
Point point = mPoints.get(pointIndex);
if (x > (point.x - mTouchTolerance) && x < (point.y + mTouchTolerance)) {
if (y > (point.y - mTouchTolerance) && y < (point.y + mTouchTolerance)) {
return true;
}
}
return false;
}
public List<Point> getPoints() {
return mPoints;
}
public void setPoints(List<Point> points) {
this.mPoints = points;
}
private int dp2px(int dp) {
Resources r = getContext().getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics());
return (int) px;
}
}
Still am I missing something?
I done something similar but I'm not sure if it's exactly what you're expecting. Try this implementation of PaintView:
Edit:
Added touch_move() to drawn line along finger move.
Edit2:
To draw multiple lines with one move change touch_move() method to this one:
private void touch_move(float x, float y) {
// draw line with finger move
if (isPathStarted) {
mPath.reset();
Point p = mPoints.get(mLastPointIndex);
mPath.moveTo(p.x, p.y);
if (checkPoint(x, y, mLastPointIndex + 1)) {
p = mPoints.get(mLastPointIndex + 1);
mPath.lineTo(p.x, p.y);
mCanvas.drawPath(mPath, mPaint);
mPath.reset();
++mLastPointIndex;
} else {
mPath.lineTo(x, y);
}
}
}
_
public class PaintView extends View {
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mPaint;
private static final int TOUCH_TOLERANCE_DP = 24;
private static final int BACKGROUND = 0xFFDDDDDD;
private List<Point> mPoints = new ArrayList<Point>();
private int mLastPointIndex = 0;
private int mTouchTolerance;
private boolean isPathStarted = false;
public PaintView(Context context) {
super(context);
mCanvas = new Canvas();
mPath = new Path();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(12);
mTouchTolerance = dp2px(TOUCH_TOLERANCE_DP);
// TODO just test points
Point p1 = new Point(20, 20);
Point p2 = new Point(100, 100);
Point p3 = new Point(200, 250);
Point p4 = new Point(280, 400);
Point p5 = new Point(350, 600);
Point p6 = new Point(400, 500);
mPoints.add(p1);
mPoints.add(p2);
mPoints.add(p3);
mPoints.add(p4);
mPoints.add(p5);
mPoints.add(p6);
}
public PaintView(Context context, AttributeSet attrs) {
super(context, attrs);
mCanvas = new Canvas();
mPath = new Path();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(12);
mTouchTolerance = dp2px(TOUCH_TOLERANCE_DP);
// TODO just test points
Point p1 = new Point(20, 20);
Point p2 = new Point(100, 100);
Point p3 = new Point(200, 250);
Point p4 = new Point(280, 400);
Point p5 = new Point(350, 600);
Point p6 = new Point(400, 500);
mPoints.add(p1);
mPoints.add(p2);
mPoints.add(p3);
mPoints.add(p4);
mPoints.add(p5);
mPoints.add(p6);
}
public PaintView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mCanvas = new Canvas();
mPath = new Path();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(12);
mTouchTolerance = dp2px(TOUCH_TOLERANCE_DP);
}
#Override
protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
super.onSizeChanged(width, height, oldWidth, oldHeight);
clear();
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(BACKGROUND);
canvas.drawBitmap(mBitmap, 0, 0, null);
canvas.drawPath(mPath, mPaint);
// TODO remove if you dont want points to be drawn
for (Point point : mPoints) {
canvas.drawPoint(point.x, point.y, mPaint);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up(x, y);
invalidate();
break;
}
return true;
}
private void touch_start(float x, float y) {
if (checkPoint(x, y, mLastPointIndex)) {
mPath.reset();
// user starts from given point so path can beis started
isPathStarted = true;
} else {
// user starts move from point which doen's belongs to mPinst list
isPathStarted = false;
}
}
//ADDED WITH LAST EDIT
private void touch_move(float x, float y) {
// draw line with finger move
if (isPathStarted) {
mPath.reset();
Point p = mPoints.get(mLastPointIndex);
mPath.moveTo(p.x, p.y);
mPath.lineTo(x, y);
}
}
/**
* Draws line.
*/
private void touch_up(float x, float y) {
mPath.reset();
if (checkPoint(x, y, mLastPointIndex + 1) && isPathStarted) {
// move finished at valid point so draw whole line
// start point
Point p = mPoints.get(mLastPointIndex);
mPath.moveTo(p.x, p.y);
// end point
p = mPoints.get(mLastPointIndex + 1);
mPath.lineTo(p.x, p.y);
mCanvas.drawPath(mPath, mPaint);
mPath.reset();
// increment point index
++mLastPointIndex;
isPathStarted = false;
}
}
/**
* Sets paint
*
* #param paint
*/
public void setPaint(Paint paint) {
this.mPaint = paint;
}
/**
* Returns image as bitmap
*
* #return
*/
public Bitmap getBitmap() {
return mBitmap;
}
/**
* Clears canvas
*/
public void clear() {
mBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
mBitmap.eraseColor(BACKGROUND);
mCanvas.setBitmap(mBitmap);
invalidate();
}
/**
* Checks if user touch point with some tolerance
*/
private boolean checkPoint(float x, float y, int pointIndex) {
if (pointIndex == mPoints.size()) {
// out of bounds
return false;
}
Point point = mPoints.get(pointIndex);
//EDIT changed point.y to poin.x in the first if statement
if (x > (point.x - mTouchTolerance) && x < (point.x + mTouchTolerance)) {
if (y > (point.y - mTouchTolerance) && y < (point.y + mTouchTolerance)) {
return true;
}
}
return false;
}
public List<Point> getPoints() {
return mPoints;
}
public void setPoints(List<Point> points) {
this.mPoints = points;
}
private int dp2px(int dp) {
Resources r = getContext().getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics());
return (int) px;
}
}
I used it from xml but you can also create it from code, simple xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<com.example.lecho.PaintView
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Here I put code of drawing object on canvas . You can draw line , circle , etc ..
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
</LinearLayout>
SampleCanvasActivity.java
public class SampleCanvasActivity extends Activity implements OnTouchListener {
DrawPanel dp;
private ArrayList<Path> pointsToDraw = new ArrayList<Path>();
private Paint mPaint;
Path path;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
dp = new DrawPanel(this);
dp.setOnTouchListener(this);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
mPaint = new Paint();
mPaint.setDither(true);
mPaint.setColor(Color.WHITE);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(3);
FrameLayout fl = new FrameLayout(this);
fl.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
fl.addView(dp);
setContentView(fl);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
dp.pause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
dp.resume();
}
public boolean onTouch(View v, MotionEvent me) {
// TODO Auto-generated method stub
synchronized(pointsToDraw)
{
if(me.getAction() == MotionEvent.ACTION_DOWN){
path = new Path();
path.moveTo(me.getX(), me.getY());
Log.e("Location", String.valueOf("x : "+ me.getX()+ "y : " +me.getY()));
//path.lineTo(me.getX(), me.getY());
pointsToDraw.add(path);
}else if(me.getAction() == MotionEvent.ACTION_MOVE){
path.lineTo(me.getX(), me.getY());
}else if(me.getAction() == MotionEvent.ACTION_UP){
//path.lineTo(me.getX(), me.getY());
}
}
return true;
}
public class DrawPanel extends SurfaceView implements Runnable{
Thread t = null;
SurfaceHolder holder;
boolean isItOk = false ;
public DrawPanel(Context context) {
super(context);
// TODO Auto-generated constructor stub
holder = getHolder();
}
public void run() {
// TODO Auto-generated method stub
while( isItOk == true){
if(!holder.getSurface().isValid()){
continue;
}
Canvas c = holder.lockCanvas();
c.drawARGB(255, 0, 0, 0);
onDraw(c);
holder.unlockCanvasAndPost(c);
}
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
synchronized(pointsToDraw)
{
for (Path path : pointsToDraw) {
canvas.drawPath(path, mPaint);
}
}
}
public void pause(){
isItOk = false;
while(true){
try{
t.join();
}catch(InterruptedException e){
e.printStackTrace();
}
break;
}
t = null;
}
public void resume(){
isItOk = true;
t = new Thread(this);
t.start();
}
}
}

how to bound set of points (custom shape) and touch event on it android

i am able to get my bitmap set of points (as an array) using this link
now my question is how can i bound these points as shape/region. Means when user touched on area of my bounded points, i want to move objects(shape) according to that. Above link return points of colored bitmap (it remove transparent part), only colored part points are return as an array.
This is what my code :
1) CustomSahpe.java
public class CustomShape {
private final Context context;
Bitmap bitmap;
int width, height;
int[] pixels;
private final ArrayList<Point> points = new ArrayList<Point>();
public CustomShape(Context context) {
// TODO Auto-generated constructor stub
// super(context);
this.context = context;
bitmap = BitmapFactory.decodeResource(context.getResources(),
R.drawable.ic_menu_balloon);
width = bitmap.getWidth();
height = bitmap.getHeight();
pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
getActualBitmap();
}
public ArrayList<Point> getPoints(){
return points;
}
public void getActualBitmap() {
for (int x = 0; x < width; x+=2) {
int firstY = -1, lastY = -1;
for (int y = 0; y < height; y+=2) {
boolean transparent = (pixels[y * width + x] == Color.TRANSPARENT);
if (!transparent) {
if (firstY == -1) {
firstY = y;
}
lastY = y;
}
}
if (firstY != -1) {
points.add(new Point(x, firstY));
points.add(new Point(x, lastY));
}
}
}
}
2) MyShapre.java
class MyShape{
CustomShape customShape ;
Point points[];
private int x, y;
Path path = new Path();
public MyShape(Context context) {
customShape = new CustomShape(ScaleTestActivity.this);
points = new Point[customShape.getPoints().size()];
for(int i=0;i<customShape.getPoints().size();i++){
points[i] = new Point();
points[i] = customShape.getPoints().get(i);
}
}
public Path getPath(){
return path;
}
public void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
Paint paint = new Paint();
paint.setColor(Color.WHITE);
for(int i =0 ;i<points.length;i++){
Point point = new Point(points[i].x + getX(), points[i].y + getY());
path.lineTo(points[i].x, points[i].y);
canvas.drawPoint(point.x,point.y,paint);
}
}
public void setX(int x) {
this.x = x;
}
public int getX() {
return x;
}
public void setY(int y) {
this.y = y;
}
public int getY() {
return y;
}
}
}
3) MainPanel.java
class MainPanel extends View{
Context context;
MyShape myShape;
boolean flag = false;
public MainPanel(Context context) {
super(context);
this.context = context;
myShape = new MyShape(context);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.RED);
myShape.onDraw(canvas);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
int x,y;
x = (int)event.getX();
y = (int)event.getY();
Point point = new Point(x, y);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
myShape.setX(x);
myShape.setY(y);
RectF rectF = new RectF();
Path path = myShape.getPath();
path.computeBounds(rectF, true);
Region region = new Region();
region.setPath(path, new Region((int) rectF.left, (int) rectF.top, (int) rectF.right, (int) rectF.bottom));
if(region.contains(x,y)){
flag = true;
Log.i("System out","onDown");
}
break;
case MotionEvent.ACTION_MOVE:
Log.i("System out","onMove : "+flag);
if(flag){
myShape.setX(x);
myShape.setY(y);
Log.i("System out","onMove");
}
break;
case MotionEvent.ACTION_UP:
// myShape.setX(x);
// myShape.setY(y);
flag = false;
Log.i("System out","onUp");
break;
default:
break;
}
invalidate();
return true;
}
}
4) ScaleTestActivity.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MainPanel(this));
}
I use a Polygon class to detect touches on rotated bitmaps. It's based mostly on information and code from this site http://alienryderflex.com/polygon/. This should work with your code.
public class Polygon {
// Polygon coodinates.
private final int[] polyY, polyX;
// Number of sides in the polygon.
private final int polySides;
/**
* Default constructor.
* #param px Polygon y coods.
* #param py Polygon x coods.
* #param ps Polygon sides count.
*/
public Polygon( final int[] px, final int[] py, final int ps ) {
polyX = px;
polyY = py;
polySides = ps;
}
/**
* Checks if the Polygon contains a point.
* #see "http://alienryderflex.com/polygon/"
* #param x Point horizontal pos.
* #param y Point vertical pos.
* #return Point is in Poly flag.
*/
public boolean contains( final float x, final float y ) {
boolean oddTransitions = false;
for( int i = 0, j = polySides -1; i < polySides; j = i++ ) {
if( ( polyY[ i ] < y && polyY[ j ] >= y ) || ( polyY[ j ] < y && polyY[ i ] >= y ) ) {
if( polyX[ i ] + ( y - polyY[ i ] ) / ( polyY[ j ] - polyY[ i ] ) * ( polyX[ j ] - polyX[ i ] ) < x ) {
oddTransitions = !oddTransitions;
}
}
}
return oddTransitions;
}
}
You could add this constructor to help you convert a Point array to a Polygon object.
public Polygon(Point[] points){
polySides = points.length;
polyY = new int[polySides];
polyX = new int[polySides];
for(int i = 0; i < polySides; i++){
polyY[i] = points[i].y;
polyX[i] = points[i].x;
}
}
You might be able to use it in your MyShape class with this method.
public boolean isTouched(final float X, final float Y){
final Polygon p = new Polygon(points);
return p.contains(X, Y);
}
Now if you have an odd shape you should be able to detect exactly if the use touches it. I have used this method many times.
Are you looking for a way to tell whether a touch event falls on the non-transparent portion of your drawn bitmap? If so, why don't you just map the touch coordinate to the proper pixel on the bitmap and test the color?
And if that's the case, then you can skip all the path clipping stuff, since the link you posted was only doing that to overcome emulator inefficiencies.
It's a bit complicated so I am not going to provide the full source but I will give you an idea.
You need to transfer your shape in to a triangles collection, then on touch find the nearest point of your shape and check if your are inside this point triangle.
For searching and sorting points you can use red-black-red tree structure.
The search algorithm eventually should be at O(log(N)) and creating shape structure should be O(N*Log(N))

How to draw multiple bitmaps on a canvas

I am having trouble with the canvas function, I have no problem drawing 1 bitmap with the canvas but as soon as I add a 2nd bitmap, it only draws the last bitmap, does not show both.
please help. here is my code.
My intent, is to then animate these 2 different bitmaps independently on the screen.
#Override
protected void onDraw(Canvas canvas) {
football = BitmapFactory.decodeResource(getResources(),
R.drawable.ballicon);
receiver = BitmapFactory.decodeResource(getResources(),
R.drawable.rec);
canvas.drawBitmap(football, translate, null);
canvas.drawBitmap(receiver, translate, null);
Matrix m = canvas.getMatrix();
Log.d(DEBUG_TAG, "Matrix: " + translate.toShortString());
Log.d(DEBUG_TAG, "Canvas: " + m.toShortString());
}
Thanks
Here is a canvasview for drawing with multiple bitmaps
public class AdvanceCanvasView extends View {
private Bitmap bitmap;
private Canvas bitmapCanvas;
private Bitmap mBitmapBrush;
private ArrayList<Bitmap> bitmapArrayList;
private Vector2 mBitmapBrushDimensions;
private Paint paintLine;
private List<Vector2> mPositions = new ArrayList<Vector2>(100);
private HashMap<Integer, Path> pathMap; // current Paths being drawn
private HashMap<Integer, Point> previousPointMap; // current Points
private int i = 0;
private static final class Vector2 {
public Vector2(float x, float y) {
this.x = x;
this.y = y;
}
public final float x;
public final float y;
}
#SuppressLint("UseSparseArrays")
public AdvanceCanvasView(Context context, AttributeSet attrs) {
super(context, attrs); // pass context to View's constructor
}
public AdvanceCanvasView(Context c) {
super(c);
pathMap = new HashMap<>();
previousPointMap = new HashMap<>();
bitmapArrayList = new ArrayList<>();
paintLine = new Paint();
}
#Override
public void onSizeChanged(int w, int h, int oldW, int oldH) {
bitmap = Bitmap.createBitmap(getWidth(), getHeight(),
Bitmap.Config.ARGB_8888);
bitmapCanvas = new Canvas(bitmap);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(bitmap, 0, 0, null);
for (int i = 0; i < mPositions.size(); i++) {
canvas.drawBitmap(bitmapArrayList.get(i), mPositions.get(i).x, mPositions.get(i).y, null);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getActionMasked();
int actionIndex = event.getActionIndex();
if (action == MotionEvent.ACTION_DOWN
|| action == MotionEvent.ACTION_POINTER_DOWN) {
touchStarted(event.getX(actionIndex), event.getY(actionIndex),
event.getPointerId(actionIndex));
}
else if (action == MotionEvent.ACTION_UP
|| action == MotionEvent.ACTION_POINTER_UP) {
touchEnded(event.getPointerId(actionIndex));
}
else {
touchMoved(event);
}
invalidate();
return true;
}
private void touchStarted(float x, float y, int lineID) {
Path path;
Point point;
path = new Path(); // create a new Path
pathMap.put(lineID, path); // add the Path to Map
point = new Point(); // create a new Point
previousPointMap.put(lineID, point); // add the Point to the Map
path = new Path(); // create a new Path
point = new Point(); // create a new Point
path.moveTo(x, y);
point.x = (int) x;
point.y = (int) y;
} // end method touchStarted
private void touchMoved(MotionEvent event) {
// for each of the pointers in the given MotionEvent
for (int i = 0; i < event.getPointerCount(); i++) {
final float posX = event.getX();
final float posY = event.getY();
mPositions.add(new Vector2(posX - mBitmapBrushDimensions.x / 2, posY - mBitmapBrushDimensions.y / 2));
bitmapArrayList.add(mBitmapBrush);
}
invalidate();
}
private void touchEnded(int lineID) {
Path path = pathMap.get(lineID);
path.reset();
}
public void init(Bitmap bitmap) {
mBitmapBrush = bitmap;
BitmapShader shader = new BitmapShader(mBitmapBrush, Shader.TileMode.MIRROR, Shader.TileMode.MIRROR);
paintLine.setShader(shader);
mBitmapBrushDimensions = new Vector2(mBitmapBrush.getWidth(), mBitmapBrush.getHeight());
}
}

Categories

Resources