这应该是一个简单的白板工具,带有缩放/平移效果。
整个路径绘制部分都没问题,只是在缩放/平移时出现了一些问题。
当对白板进行缩放时,无论我怎么做,所有在缩放之后的线条都会相对于我实际绘制的位置发生位移。
我将尽可能详细地说明情况,不显示不必要的代码,但这是一篇相当长的文章,请耐心阅读。
因为一张图片胜过千言万语,我将用图示来说明情况:
所以,我尝试了许多不同的方法,但都没有成功。
现在进入技术部分,这是我目前正在做的:
它是通过扩展View来实现的。
我只使用onDraw方法来执行应用笔画的“动画”:
@Override
public void onDraw(Canvas canvas)
{
super.onDraw(canvas);
if(isDrawing)
{
canvas.drawPath(mPath, mPaint);
canvas.drawBitmap(mBitmap, 0, 0, mPaint);
}
}
我有两个ImageView,用于在绘制和缩放完成后放置生成的位图。我使用两个视图的原因是为了交换它们,以便始终在绘制渲染时有一个可用的视图。
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:visibility="visible"
android:scaleType="matrix" />
<ImageView
android:id="@+id/imageView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:visibility="visible"
android:scaleType="matrix" />
在画布上绘制完毕后,我将给定的位图发送到我的视图中,然后清除画布以便进行更多的绘制:
private void sendImage2BackView()
{
//veeery extensive and boring code surpressed here
//set the entire hocus-pocus' resulting bitmap as a resource for my view
mView.setImageBitmap(tempBmp);
mView.bringToFront();
}
我实现了一个扩展了 ScaleGestureDetector.SimpleOnScaleGestureListener 的 ScaleListener 类。
在 onScale 时刻,我会告诉我的画布我的缩放比例是多少:
@Override
public boolean onScale(ScaleGestureDetector detector)
{
drawAction = ZOOM;
scaleFactor *= detector.getScaleFactor();
scaleFactor = Math.max(MIN_ZOOM, Math.min(scaleFactor, MAX_ZOOM));
canvas.setScaleFactor(scaleFactor);
return true;
}
然后,在我的视图(画布对象)中,我只需将比例设置为正在使用的视图:
mView.setScaleX(factor);
mView.setScaleY(factor);
现在,最重要的部分来了,在 onScaleEnd 中,我调用一个方法,试图获取当前画布位图 AS IS,并将其发送到我的视图中,与其兄弟们和平共处,每个都有自己的大小和偏移量。
public void setScaleEnd()
{
//Lots of more boring code surpressed here
//....
//I store the bitmap that was contained at the ImageView
// IF anyone is present
previousBmp = ((BitmapDrawable)mView.getDrawable()).getBitmap();
//then, I create a brand new scaled bitmap,in order to
// acquire the same proportion of ZOOM that I've just applied
tempBmp = Bitmap.createScaledBitmap(previousBmp,
(int)(mView.getWidth()*scaleFactor),
(int)(mView.getHeight()*scaleFactor), true);
int height = (int)(mView.getHeight()*scaleFactor);
int width = (int)(mView.getWidth()*scaleFactor);
//set my matrix
mMatrix = new Matrix();
//give it the right proportion
mMatrix.postScale(scaleFactor, scaleFactor);
translationX = mView.getWidth() / 2 - width / 2;
translationY = mView.getHeight() / 2 - height / 2;
//give it some necessary translation amount
mMatrix.postTranslate(translationX, translationY);
//set the matrix to the view, and send the resized bitmap to my ImageView.
mView.setImageMatrix(mMatrix);
mView.setImageBitmap(tempBmp);
}
现在,我已经尝试过将所有东西直接显示在画布上,并给它一个比例/平移量;也尝试着分别处理位图,然后将它们发送回新的干净画布。
但是,当应用一定的缩放量后,我仍然保持着笔画上的位移!!! 我只想画一些东西,进行缩放,继续画更多的东西,并使笔划停留在我正在绘制的位置!
这可能吗?
我刚刚在玩S Note应用程序,它完全符合我试图实现的目标。