最近在做相册的图片编辑功能,遇到一个bug,插入文字后旋转文字区域,点击文字区域无法触发,分析原因是判断时认定为点没在RectF内。如图:
如果只是通过rect.contains(x, y)来判断,那么实际区域则是绿色区域的部分,则有部分无法点击,如下图:
因此需要将矩形框旋转。
如果通过matrix.mapRect(rect)来获取转换后的区域,再通过rect.contains(x, y)来判断是否落在区域内,那么实际区域如下图绿色区域,则点击非区域内的位置仍会触发文字区域的点击,如下图:
Matrix matrix = new Matrix();
matrix.setRotate(roatetAngle, mHelpBoxRect.centerX(), mHelpBoxRect.centerY());
matrix.mapRect(mHelpBoxRect);
因此,无法通过rect.contains(x, y)来判断点是否落在区域内。需要将原矩形四个顶点旋转,将转换后的矩形四个顶点重新构成四边形,再判断点是否落在该四边形内。
public boolean clickHelpBoxRect(float x, float y) {
if (mHelpBoxRect == null || mHelpBoxRect.isEmpty()) {
return false;
}
boolean isClickHelpBoxRect;
if (roatetAngle != 0) {
// 旋转后判断点是否在四边形内
Matrix matrix = new Matrix();
matrix.setRotate(roatetAngle, mHelpBoxRect.centerX(), mHelpBoxRect.centerY());
PointF curPoint = new PointF(x, y);
PointF pointLT = getMapPoints(matrix, mHelpBoxRect.left, mHelpBoxRect.top);
PointF pointRT = getMapPoints(matrix, mHelpBoxRect.right, mHelpBoxRect.top);
PointF pointLB = getMapPoints(matrix, mHelpBoxRect.left, mHelpBoxRect.bottom);
PointF pointRB = getMapPoints(matrix, mHelpBoxRect.right, mHelpBoxRect.bottom);
isClickHelpBoxRect = pointInRect(curPoint, pointLT, pointRT, pointLB, pointRB);
} else {
isClickHelpBoxRect = mHelpBoxRect.contains(x, y);
}
return isClickHelpBoxRect;
}
/**
* 获取旋转后的坐标点
*
* @param matrix 转换矩阵
* @param x 左坐标
* @param y 右坐标
* @return
*/
private PointF getMapPoints(Matrix matrix, float x, float y) {
float[] floats = new float[]{x, y};
matrix.mapPoints(floats);
return new PointF(floats[0], floats[1]);
}
/**
* 点是否落在四边形内
*
* @param curPoint 点击位置
* @param pointLT 左上顶点
* @param pointRT 右上顶点
* @param pointLB 左下顶点
* @param pointRB 右下顶点
* @return true 在四边形内;false 不在四边形内
*/
private boolean pointInRect(PointF curPoint, PointF pointLT, PointF pointRT, PointF pointLB, PointF pointRB) {
int nCount = 4;
PointF[] rectPoints = new PointF[]{pointLT, pointLB, pointRB, pointRT};
int nCross = 0;
for (int i = 0; i < nCount; i++) {
//依次取相邻的两个点
PointF pStart = rectPoints[i];
PointF pEnd = rectPoints[(i + 1) % nCount];
//相邻的两个点是平行于x轴的,肯定不相交,忽略
if (pStart.y == pEnd.y)
continue;
//交点在pStart,pEnd的延长线上,pCur肯定不会与pStart.pEnd相交,忽略
if (curPoint.y < Math.min(pStart.y, pEnd.y) || curPoint.y > Math.max(pStart.y, pEnd.y))
continue;
//求当前点和x轴的平行线与pStart,pEnd直线的交点的x坐标
double x = (double) (curPoint.y - pStart.y) * (double) (pEnd.x - pStart.x) / (double) (pEnd.y - pStart.y) + pStart.x;
//若x坐标大于当前点的坐标,则有交点
if (x > curPoint.x)
nCross++;
}
// 单边交点为偶数,点在多边形之外
return (nCross % 2 == 1);
}