画布旋转时的getbounds
问题描述:
我需要获取画布内部图像的边界以检测是否已被触摸,但如果旋转画布,getbounds()会保持相同的值,那么我如何获取画布旋转后的正确值?画布旋转时的getbounds
//CODE ON VIEW CLASS:
canvas.save();
canvas.rotate(rotation, Xpos, Ypos);
secHandImg.setBounds(left,top,right,bottom);
secHandImg.setAntiAlias(true);
secHandImg.draw(canvas);
circleHandImg.setBounds(left,top,right,bottom);
circleHandImg.setAntiAlias(true);
circleHandImg.draw(canvas);
canvas.restore();
//CODE ON FRAGMENT CLASS:
public boolean onTouch(View view, MotionEvent event) {
Rect imageBounds = MyClass.secHandImg.getBounds();
int action = event.getAction();
final int x = (int)event.getX();
final int y = (int)event.getY();
if(action == MotionEvent.ACTION_DOWN) {
if(x >= imageBounds.left && x < (imageBounds.left + imageBounds.width())
&& y >= imageBounds.top && y < (imageBounds.top + imageBounds.height())){
//THIS DON´T WORK IF CANVAS ROTATES
imageBoundsTouch = true;
}
}
这里的图像更好地说明我的问题:
答
可以使用三角得到旋转矩形的界限:
function BBoxDimensions(width,height,radianAngle){
var c = Math.abs(Math.cos(radianAngle));
var s = Math.abs(Math.sin(radianAngle));
return({ width: height * s + width * c, height: height * c + width * s });
}
而且你可以使用三克至获得XY旋转边框:
// where cx/cy is the center of rotation of the target
// and startingX/startingY is the starting xy of the unrotated target
var x1 = startingX - cx;
var y1 = startingY - cy;
newX =cx+ x1*Math.cos(angle) - y1*Math.sin(angle);
newY =cy+ y1*Math.cos(angle) + x1*Math.sin(angle);
谢谢!我会试着看到你的形象吗? – jisdroid 2013-04-24 21:38:58
它不工作我需要的位置在屏幕上,而不是矩形的大小 – jisdroid 2013-04-25 21:49:49
请参阅我编辑的帖子,显示旋转边界框的xy。 – markE 2013-04-25 22:10:57