android - Canvas 旋转时获取边界

标签 android canvas rotation

我需要获取 Canvas 内图像的边界以检测是否已被触摸,但是如果我旋转 Canvas ,getbounds() 将保持相同的值,我如何在 Canvas 后获得正确的值旋转?

//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;


                }

        }   

这里有一张图片可以更好地解释我的问题:

http://s11.postimg.org/z7j0xgwmb/Imagen_2.png

最佳答案

您可以使用三角函数来获取旋转矩形的边界:

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

并且您可以使用 trig 获取旋转边界框的 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);

关于android - Canvas 旋转时获取边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16202030/

相关文章:

android - 在 Android 上,是否可以在对话框中显示数据表?

java - 如何区分元素?

javascript - 在 HTML 中单击按钮时,JS 变量不会更新

java - 为什么这段代码只旋转正方形?

java - Android:在 3 个 Activity 之间传递相同的变量?

android - 在某些页面上强制方向

javascript - DrawImage 不显示 CSS 样式

javascript - Canvas 添加事件监听器点击图片

iphone - 拖动 UIButton 时 UIView 改变框架

ios - UIDevice 设置方向在 iPad 上不起作用