【问题标题】:Rotate a rect on canvas on user touch在用户触摸时在画布上旋转矩形
【发布时间】:2017-12-06 05:40:10
【问题描述】:

我尝试在网上查了很多关于此的信息,但找不到任何解决方案。我想在用户拖动bottom-right 角(指向图像)时旋转rectrotation 的中心应该与rect 的中心相同。

【问题讨论】:

  • 你的问题是什么?
  • 如何旋转矩形??
  • 我在聊天中发给你的文件怎么样。你检查过那个文件@ pskink

标签: android android-canvas


【解决方案1】:

您可以使用画布旋转。

//Example


Path path = new Path();
path.addRect(166, 748, 314, 890, Path.Direction.CW);
canvas.save(); // first save the state of the canvas
canvas.rotate(45); // rotate it
canvas.drawPath(path, paint); // draw on it
canvas.restore(); // restore previous state (rotate it back)

Android Implement onTouchListener on path objects 检查此链接。你可以override onTouchEvent()

【讨论】:

  • 它总是将画布旋转 45 度,我想根据用户旋转它
  • 检查更新的答案
  • 但这仍会将画布旋转 45 度
  • @NirmalPrajapat 您可以将 45 更改为所需的值,例如 canvas.rotate(75);它将旋转 75 度
  • 如果用户拖动矩形的右下角@WaleedAsim,如何找到该角度
【解决方案2】:

确定旋转角度的一般方法:

rotation center coordinates xc, yc

on touch (mouse) down: 
  check whether touch point is in grab region
  remember coordinates x0, y0
  set flag "InRotation"

on touch move:
  current coordinates x1, y1
  check if (they are in allowed region) and (InRotation is set)
    calculate rotation angle as
       alpha = Math.atan2((x1-xc)*(y0-yc) - (x0-xc)*(y1-yc), 
                            (x1-xc)*(x0-xc) + (y0-yc)*(y1-yc))
    redraw image using alpha angle

on touch up:
 clear InRotation flag
 make actions after rotation if needed

请注意,您必须在仿射矩阵计算中使用旋转中心坐标才能正确绘制旋转矩形:

 canvas.save();
 canvas.rotate(alpha, xc, yc);
 canvas.drawRect(.....);
 canvas.restore();

【讨论】:

  • ArcTan2 是什么意思?是 atan2() 吗??
  • 是的,它是 atan2。而且我不知道 - 结果可能是您的语言中的弧度(而不是度数)。
  • xc 和 yc 是矩形的中心??
  • 是的,xc 和 yc 是矩形的中心,如果你围绕它的中心旋转矩形
  • ((x1-xc)*(y0-yc) - (x0-xc)*(y1-yc), (x1-xc)*(x0-xc) + (y0-xc) *(y1-yc))你确定这个公式是正确的???..请再检查一次。我对此有疑问
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-07
  • 1970-01-01
  • 2021-10-07
  • 2016-07-20
  • 1970-01-01
  • 2011-10-26
  • 2016-08-05
相关资源
最近更新 更多