如何找到在画布当前的翻译位置? [英] How to find the current translate position in Canvas?

查看:164
本文介绍了如何找到在画布当前的翻译位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何获取当前翻译从画布的位置?我想画的东西在我的坐标是相对的混合(彼此)和绝对(帆布)。

How do I get the current translate position from a Canvas? I am trying to draw stuff where my coordinates are a mix of relative (to each other) and absolute (to canvas).

可以说,我想做的事情

canvas.translate(x1, y1);
canvas.drawSomething(0, 0); // will show up at (x1, y1), all good
// now i want to draw a point at x2,y2
canvas.translate(x2, y2);
canvas.drawSomething(0, 0); // will show up at (x1+x2, y1+y2)
// i could do
canvas.drawSomething(-x1, -y1);
// but i don't always know those coords

这工作,但脏了:

private static Point getCurrentTranslate(Canvas canvas) {
    float [] pos = new float [2];
    canvas.getMatrix().mapPoints(pos);
    return new Point((int)pos[0], (int)pos[1]);
}
...
Point p = getCurrentTranslate(canvas);
canvas.drawSomething(-p.x, -p.y);

画布有getMatrix方法,它有一个 setTranslate ,但没有 getTranslate 。我不想使用 canvas.save() canvas.restore(),因为我的方式绘制的东西它是一个有点棘手(也可能是凌乱...)

The canvas has a getMatrix method, it has a setTranslate but no getTranslate. I don't want to use canvas.save() and canvas.restore() because the way I'm drawing things it's a little tricky (and probably messy ...)

有一个更清洁的方式来获得这些当前坐标?

Is there a cleaner way to get these current coordinates?

推荐答案

您需要先重新设置变换矩阵。我不是一个Android开发者,看着 Android的画布文档,没有复位矩阵,但有一个setMatrix(android.graphics.Matrix)。它说,如果给定矩阵是空它将设置当前矩阵为单位矩阵,这是你想要的。所以我觉得你可以重置您的位置(和比例和倾斜):

You need to reset the transformation matrix first. I'm not an android developer, looking at the android canvas docs, there is no reset matrix, but there is a setMatrix(android.graphics.Matrix). It says if the given matrix is null it will set the current matrix to the identity matrix, which is what you want. So I think you can reset your position (and scale and skew) with:

canvas.setMatrix(null);

也将是可能的,通过getMatrix来得到当前翻译。有一个mapVectors()方法,你可以使用矩阵,看看点[0,0]将被映射成,这将是您的翻译。但是,在你的情况我想重置矩阵是最好的。

It would also be possible to get the current translation through getMatrix. There is a mapVectors() method you could use for matrices to see where the point [0,0] would be mapped to, this would be your translation. But in your case I think resetting the matrix is best.

这篇关于如何找到在画布当前的翻译位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆