2014-06-24 226 views
0

我想使用Canvas类在Android中填充三角形。我目前的做法是有效的,但非常滞后。我想知道是否有人比我的方式更快地做到这一点。谢谢!绘制旋转三角形

我的代码:

public void rotate(float angle){ 
    if(neighbour == null) 
     return; 
    path.reset(); 
    Point origin = rotatePoint(neighbour.getX() + 64, neighbour.getY() + 128 + 16, neighbour.getX() + 64, neighbour.getY() + 64, angle); 
    Point a = rotatePoint(neighbour.getX() + 64, neighbour.getY() + 128 + neighbour.getWidth() + neighbour.getHeight(), neighbour.getX() + 64, neighbour.getY() + 64, angle - 15); 
    Point b = rotatePoint(neighbour.getX() + 64, neighbour.getY() + 128 + neighbour.getWidth() + neighbour.getHeight(), neighbour.getX() + 64, neighbour.getY() + 64, angle + 15); 
    path.moveTo(origin.x, origin.y); 
    path.lineTo(a.x, a.y); 
    path.lineTo(b.x, b.y); 
} 

邻居只是持有xy值的一类。

旋转点法:

private Point rotatePoint(float x, float y, float px, float py, float angle){ 
    float s = (float)Math.sin(Math.toRadians(angle)); 
    float c = (float)Math.cos(Math.toRadians(angle)); 

    x -= px; 
    y -= py; 

    float xnew = x * c - y * s; 
    float ynew = x * s + y * c; 

    x = xnew + px; 
    y = ynew + py; 
    return new Point((int)x, (int)y); 
} 

这个三角形将相当频繁旋转,所以我需要做的一个有效方式。

回答

1

只能用相同的路径绘制三角形,但在绘制路径之前,将画布旋转到所需的旋转角度。

canvas.save(); 
canvas.rotate(degrees); 
//draw your triangle here 
canvas.restore(); 

还有一个

canvas.rotate(degrees, x, y); 

,如果你需要给它一个支点。

+0

谢谢,完全忘了这个功能!我会抽出时间试试看。 – TameHog