版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xxdddail/article/details/89088659
android的图形绘制是基于canvas,旋转也是对canvas进行旋转,但是因为旋转是直接旋转了canvas,所以必须在旋转前保存(save),然后再旋转后再恢复(restore),否则后续的图形都会绘制在旋转后的canvas上。示例代码如下
/**
* 绘制图形
*
* @param canvas
*/
private void drawGraphic(Canvas canvas) {
canvas.save();//旋转前需要保存原有状态
Bitmap bmp = Bitmap;//Bitmap是要绘制的位图
Rect rectSrc = new Rect(0, 0, bmp.getWidth(), bmp.getHeight());
Rect rectDst = new Rect((int) Center.X, (int) Center.Y, (int) Center.X + Width, (int) Center.Y + Height);
canvas.rotate(_rotateDegree, Center.X + Width / 2, Center.Y + Height / 2);//绕中心点旋转
canvas.drawBitmap(bmp, rectSrc, rectDst, _paint);
canvas.restore();//旋转后需要恢复旋转前的状态
}
在canvas.rotate设置旋转的中心点,比如绕图形的中心旋转。其中Center是一个包含了X和Y的坐标类。
/**
* 坐标
*/
public class Coordinate {
/**
* X
*/
public float X;
/**
* Y
*/
public float Y;
public Coordinate(){
X=0;
Y=0;
}
public Coordinate(float x,float y)
{
X=x;
Y=y;
}
}
在图形旋转后还要判断触摸点是否在图形内,这时需要用到矩阵来判断,示例代码如下
public boolean isIn(MotionEvent motionEvent) {
if (Bitmap == null) {
return null;
}
RectF rect = new RectF(Center.X, Center.Y, Center.X + Width, Center.Y + Height);
if (_rotateDegree != 0) {
Matrix matrix = new Matrix();
matrix.setRotate(_rotateDegree, Center.X + Width / 2, Center.Y + Height / 2);//设置旋转角度时,一定要记得设置旋转的中心,该中心与绘图时的中心点是一致的。
matrix.mapRect(rect);
}
int x = (int) motionEvent) .getRawX();
int y = (int) motionEvent) .getRawY();
if (rect.contains(x, y)) {
return true;
} else {
return false;
}
}
在拖动的过程中,已经捕获到了MotionEvent.ACTION_MOVE事件,但是没有连续触发,很可能是因为Canvas是自定义的View,而View的clickable没有设置为true,或者代码中没有设置this.setClickable(true)。
转载请注明出处。