首页 > 解决方案 > 如何在画布上平移和旋转位图?

问题描述

我正在尝试在视图的 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);
    }

标签: androidmatrixcanvasbitmap

解决方案


问题是我对旋转的计算是错误的。(Math.asin(x / xVe​​locity) 的结果是 NaN,因此旋转始终为 0。


推荐阅读