android如何通过路径在画布上绘制三角形

时间:2011-08-11 10:19:16

标签: android canvas

我可以在Action_down中为触摸事件绘制一个三角形,如下图,

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());

表示三角形尺寸已修复。

但我希望在Action_Move中,如果在画布上移动,三角形大小应该增大或减小。 我怎样才能做到这一点? 给我一个方法。 谢谢

2 个答案:

答案 0 :(得分:1)

将简单的affine transformation或简单的homothety应用于三角形。

我想你想要放大/缩小无法捏合。假设你的缩放方法计算一个因子。

然后使用此因子绘制三角形。例如:

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());

当然,这是最简单的实现。要产生更逼真的效果,您必须使用perspective projection。在这种情况下,您应该使用OpenGL并在3D中绘制三角形。

答案 1 :(得分:0)

这是我想出的一个简单解决方案,矩形大小会随着您的手指移动而变化,就像我们在半径的帮助下在画布上绘制圆形一样,让我们​​实现相同的技术

//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)
    );
}