android - 如何在画布上平移和旋转位图?
问题描述
我正在尝试在视图的 onDraw() 方法中在画布上绘制位图。位图应该在画布边缘移动和反弹,并且应该朝着移动的方向旋转。(如下图所示)
我尝试了以下代码。移动是正确的,但位图不旋转。我还尝试了具有相同输出的 preRotate 和 setRotate 而不是 postRotate。我究竟做错了什么?
public class AnimatedView extends AppCompatImageView {
private Context mContext;
int x = -1;
int y = -1;
private Handler h;
private int xVelocity = 15;
private int yVelocity = 15;
private Matrix matrix = new Matrix();
private long FRAME_RATE = 25;
private int rotation = 0;
public AnimatedView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
h = new Handler();
}
private Runnable r = this::invalidate;
protected void onDraw(Canvas c) {
BitmapDrawable mouse = (BitmapDrawable) mContext.getResources().getDrawable(R.drawable.mouse0001);
c.drawColor(getResources().getColor(R.color.dark));
rotation = (int) ((Math.asin(x / xVelocity)) / (Math.PI / 90));
if (x < 0 && y < 0) {
x = 0;
y = 0;
rotation = 180 -2 * rotation;
} else {
x += xVelocity;
y += yVelocity;
if ((x > this.getWidth()) || (x < 0 - mouse.getBitmap().getWidth())) {
xVelocity = xVelocity * -1;
rotation = 180 -2 * rotation;
}
if ((y > this.getHeight()) || (y < 0 - mouse.getBitmap().getHeight())) {
yVelocity = yVelocity * -1;
rotation = 180 -2 * rotation;
}
}
matrix.postRotate(rotation, mouse.getBitmap().getWidth()/2, mouse.getBitmap().getHeight()/2);
matrix.setTranslate(x, y);
c.drawBitmap( mouse.getBitmap(), matrix, null);
h.postDelayed(r, FRAME_RATE);
}
解决方案
问题是我对旋转的计算是错误的。(Math.asin(x / xVelocity) 的结果是 NaN,因此旋转始终为 0。
推荐阅读
- android - Salesforce Marketing Cloud 是否支持 Android 应用程序链接
- javascript - 如果滚动为 100 像素,则将背景变为红色。(纯 JavaScript)
- python-3.x - 在 Tkinter GUI 框架中显示绘图
- bash - 排序 - 在排序列表中以相同字母开头的每个组前面加上任意字符串
- android - android中的多个按钮处理
- r - 源代码中的 uniroot() 函数在修改后不起作用;无法找出错误
- api - Telegram Bots:我现在可以开始聊天吗?
- powershell - 使用 maven 部署 zip 文件
- awk - 用于解析文件并以字母格式列出输出的 AWK 命令,包括每个项目的计数
- bash - 计算连续字符数的代码