gpt4 book ai didi

java - 绘制旋转三角形

转载 作者:行者123 更新时间:2023-11-30 02:49:47 25 4
gpt4 key购买 nike

我想在 Android 中使用 Canvas 类填充一个三角形。我目前的工作方式有效但非常滞后。我想知道是否有人有比我的方法更快的方法。谢谢!

我的代码:

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

neighbor 只是一个包含 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);
}

这个三角形会非常频繁地旋转,所以我需要一种有效的方法。

最佳答案

您可以始终使用相同的路径绘制三角形,但在绘制路径之前将 Canvas 旋转到所需的旋转角度。

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

还有一个

canvas.rotate(degrees, x, y);

如果你需要给它一个轴心点。

关于java - 绘制旋转三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24397632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com