视图的onDraw方法被调用了太多次

时间:2014-04-22 21:15:53

标签: android performance layout pinchzoom pinch

我有一个Horizo​​ntalScrollView,里面有多个自定义视图。我正在Horizo​​ntalScrollView中检测pinch zoom事件并将ScaleFactor传递给子视图。我想根据其父级提供的ScaleFactor缩放子视图。

所以我正在做这样的事情。

子视图中有两个变量:localScaleFactor和 首先,我从其父级获取parentScalefactor。然后在自定义视图的onDraw方法中我喜欢缩放视图

localScaleFactor * = parentScalefactor canvas.scale(localScaleFactor,localScaleFactor);

但是由于我的onDraw函数多次调用localScaleFactor的速度非常快,即使我是单次动物园,也是如此。

父捏缩放监听器

        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));
//sending pinch zoom event to its child index 'start' to 'last'
            for(int i=start;i<=last;i++)
            {
                LinearLayout ll=(LinearLayout)pp.getChildAt(i);
                DrawView view=(DrawView)ll.findViewById(R.id.drawview);
                view.mScaleFactor=mScaleFactor; //setting child scalefactor
                view.invalidate();
            }


            return true;
        }
    }

子视图onDraw方法

        public  float mScaleFactor = 1.f; //this will be set by parent viewgroup

 public  float sf = 1.f; //local scalefactor
    public float oldsf=1.f;
    @Override

    public void onDraw(Canvas canvas) {


        sf=(mScaleFactor/oldsf);
        width=sf*700;
        paint.setColor(Color.GREEN);
        canvas.save();

        canvas.scale(sf , 1);

        Log.e("Ronak","DrawView "+sf);
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.BLUE); 
        canvas.drawRect(r, paint);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.BLACK);
        canvas.drawRect(r, paint);


        requestLayout();
        oldsf=mScaleFactor;

       } 

1 个答案:

答案 0 :(得分:0)

我看到它现在正在查看ScaleGestureDetector文档http://developer.android.com/reference/android/view/ScaleGestureDetector.html#getScaleFactor%28%29发生的事情是,对getScaleFactor()的调用返回给定时间点的比例因子,而不是我们之前断言的求和。这样做的原因是你的mScaleFactor *= detector.getScaleFactor();应该只是mScaleFactor = detector.getScaleFactor();每次你这样做时,每次应用的比例值都是每个比例因子遭遇而不是个体的产物比例因子本身。如果你在没有我之前的建议的情况下回到旧代码并更改一行代码,我相信它应该可以正常工作。对不起之前的虚假踪迹。 -Jackson