我正在尝试在我的应用中实现放大。但我遇到了困难。
到目前为止我做了什么:
(注意:这个应用程序是游戏,因此它不使用invalidate
而是使用线程)
渲染和缩放:
public void render(Canvas c) {
super.draw(c);
if (c != null) {
int ss = c.getSaveCount();
c.scale(scaleFactor, scaleFactor);
//Rendering stuff
c.restoreToCount(ss);
}
}
当前缩放:
(当有两个指针时,这是从master类中的onTouchEvent调用的。这些类是嵌套的。)
class scaler extends ScaleGestureDetector {
public scaler(Context context, OnScaleGestureListener listener) {
super(context, listener);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
listener.onScale(this);
return super.onTouchEvent(event);
}
@Override
public float getScaleFactor() {
return super.getScaleFactor();
}
}
float startScale;
float endScale;
class ScaleListener implements ScaleGestureDetector.OnScaleGestureListener{
@Override
public boolean onScale(ScaleGestureDetector detector) {
startScale = detector.getScaleFactor();
scaleFactor *= detector.getScaleFactor();
scaleFactor = (scaleFactor < 1 ? 1 : scaleFactor); // prevent our view from becoming too small //
scaleFactor = ((float)((int)(scaleFactor * 100))) / 100; // Change precision to help with jitter when user just rests their fingers //
return true;
}
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
return true;
}
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
}
}
我一直在寻找有关SO的几个问题,而我发现的所有问题都无法正常运行。解决方案有多种原因。
我目前正在使用的那个:
在缩小之前放大(缩放比例因子在缩小之前下降)
它不会放大手指所在的区域。
那么我怎样才能添加放大手指所在区域的缩放比例,然后在不重置缩放的情况下进行缩放以使其真正放大?
答案 0 :(得分:1)
感谢@pskink,以下是我为解决问题所做的工作:
onTouchEvent
,也不要调用OnScaleGestureListener.onScale,因为检测器会自动完成。{li> 这解决了缩放时遇到的问题。
至于放大特定区域,我不得不放弃使用.setScale,而是使用矩阵:
public void render(Canvas c) {
super.draw(c);
if (c != null) {
c.setMatrix(scaleMatrix);//scale
//Null the matrix = set to default.
c.setMatrix(null);//Past this line, anything rendered is not scaled.
}
}
(GestureDetector不应覆盖onTouchEvent并调用侦听器)
在听众中:
public boolean onScale(ScaleGestureDetector detector) {
startScale = detector.getScaleFactor();
scaleFactor *= detector.getScaleFactor();
if(scaleFactor > 2) scaleFactor = 2;//Limit max
else if(scaleFactor < 0.3f) scaleFactor = 0.3f;//limit min
scaleFactor = ((float)((int)(scaleFactor * 100))) / 100;//jitter-protection
scaleMatrix.setScale(scaleFactor, scaleFactor, detector.getFocusX(), detector.getFocusY());//setScale, as I don't need to scale several things.
return true;
}