我有一个HorizontalScrollView
其中有多个视图。我已经实施了pinch zoom gesture
其中我的两根手指之间的多个视图被缩放。
但我面临一个小问题。当我进行捏缩放时,捏缩放的中点正在移动,但为了用户体验,我希望该点保持固定,其他内容应在缩放时自行调整,以便中点保持静态。
有人可以告诉我该怎么做吗?
onDraw()
自定义视图的方法是
Rect r =new Rect(0, 0, 700, 40);
public void onDraw(Canvas canvas) {
float kk=mScaleFactor; //this variable will be set by pinch zoom event and represent how much to scale
sf*=kk; // this view must scale according to previous scaling
canvas.save();
canvas.scale(sf , 1);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.BLUE);
canvas.drawRect(r, paint);
width=sf*700;
canvas.restore();
requestLayout(); //this will change view width to fit the expanded rectangle
}
onMeasure 方法在 requestLayout 上调用
@Override protected void onMeasure(int widthMeasureSpec,
int heightMeasureSpec) {
setMeasuredDimension((int)width, 340);
}
上面的自定义视图被 的子类调用了 12 次HorizontalScrollView
。所以有 12 个子视图HorizontalScrollview
.
在这堂课上我正在做以下事情
检测两个手指的触摸坐标。
计算第一个手指触摸的子视图的索引。
计算第二根手指触摸的子视图的索引。
将捏缩放的比例因子传递给开始和最后之间的所有子视图。
这两个指标是在前两步中计算出来的。
最后在子视图上调用 invalidate() 。因此子视图可以根据父视图传递的比例因子来缩放自身。
但这里有一个问题。两个手指的中点应保持静止,其他部分应在缩放过程中进行调整。但我的中心点是随着规模的扩大而变化。
有人可以帮我做这件事吗?请告诉我是否需要代码的任何部分。
手势监听代码HorizontalScrollview
is
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor();
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));
ViewGroup pp=takeparent(); //give object of this class
for(int i=start;i<=last;i++)
{
LinearLayout ll=(LinearLayout)pp.getChildAt(i);
DrawView view=(DrawView)ll.findViewById(R.id.drawview);
view.mScaleFactor=mScaleFactor;
view.invalidate();
view.donesf=true;
}
Sample app of mine
按照评论中的建议进行编辑:
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor();
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));
ViewGroup pp=takeparent(); pp contains all the custom child views
//start and last are indices of range of child for which we have to apply gesture
for(int i=start;i<=last;i++)
{
LinearLayout ll=(LinearLayout)pp.getChildAt(i);
DrawView view=(DrawView)ll.findViewById(R.id.drawview);
view.mScaleFactor=mScaleFactor;
view.pivotx=detector.getFocusX()+view.getLeft();
view.pivoty=detector.getFocusY()+view.getTop();
view.invalidate();
}
return true;
}
这是自定义视图的onDraw方法
public void onDraw(Canvas canvas) {
sf=mScaleFactor //this scale factor is set by parent view
width=sf*700; //this width will be use to rescale the view's width in requestLayout()
canvas.save();
canvas.scale(sf,1,pivotx,pivoty); //pivotX and pivotY are also set by parent's onScale method of gestureListener
canvas.drawRect(r, paint);
requestLayout();
canvas.restore();
}