Jyosna
Jyosna

Reputation: 4446

android how to draw triangle on a canvas through path

I am able to draw a triangle for touch event in Action_down, like bellow,

path.moveTo(motionEvent.getX(), motionEvent.getY());
path.lineTo(motionEvent.getX()-40, motionEvent.getY()+60);
path.lineTo(motionEvent.getX()+40, motionEvent.getY()+60);
path.lineTo(motionEvent.getX(), motionEvent.getY());

that means triangle size is fix.

But i want in Action_Move the triangle size should be increase or decrease if move on the canvas. How can i do that? giv me a way. Thanks

Upvotes: 1

Views: 4015

Answers (2)

Mubashir Murtaza
Mubashir Murtaza

Reputation: 337

here is a simple solution i figured , the rectangle size will change as your finger moves , just like we draw circle on canvas with the help of radius ,lets implement same tech

//call this function from onmotion_event_move, pass x,y event
public void drawTriangle(int x, int y) {

    int halfWidth =  (int) calculateRadius(x,y,this.startX,this.startY);
    Path path = new Path();
    path.reset();
    path.moveTo(this.startX,this.startY-halfWidth);
    path.lineTo(this.startX - halfWidth, this.startY + halfWidth); // Bottom left
    path.lineTo(this.startX + halfWidth, this.startY + halfWidth); // Bottom right
    path.lineTo(this.startX, this.startY-halfWidth); // Back to Top
    path.close();

}



//this function will calculate the radius
//x1 : is the x of moving finger
//y1 : is the y of moving finger
//x2 : is the x of finger (when you put the finger down) save this point on 
//action_down
//y2 : is the y of finger (when you put the finger down) save this point on 
//action_down
private float calculateRadius(float x1, float y1, float x2, float y2) {

    return (float) Math.sqrt(
            Math.pow(x1 - x2, 2) +
                    Math.pow(y1 - y2, 2)
    );
}

Upvotes: 0

rockeye
rockeye

Reputation: 2773

Apply a simple affine transformation or simply a homothety to you triangle.

I guess you want to zoom in/out unsing pinch. Let say your zoom method computes a factor.

Then draw your triangle using this factor. For example :

path.moveTo(motionEvent.getX(), motionEvent.getY());
path.lineTo(motionEvent.getX()-40*factor, motionEvent.getY()+60*factor);
path.lineTo(motionEvent.getX()+40*factor, motionEvent.getY()+60*factor);
path.lineTo(motionEvent.getX(), motionEvent.getY());

Of course, this is the most trivial implementation. To produce more realistic effects, you will have to use a perspective projection. In this case, you should use OpenGL and draw your triangle in 3D.

Upvotes: 1

Related Questions