private ImmutableViewportMetrics getValidViewportMetrics( ImmutableViewportMetrics viewportMetrics) { /* First, we adjust the zoom factor so that we can make no overscrolled area visible. */ float zoomFactor = viewportMetrics.zoomFactor; RectF pageRect = viewportMetrics.getPageRect(); RectF viewport = viewportMetrics.getViewport(); float focusX = viewport.width() / 2.0f; float focusY = viewport.height() / 2.0f; float minZoomFactor = 0.0f; float maxZoomFactor = MAX_ZOOM; ZoomConstraints constraints = mTarget.getZoomConstraints(); if (constraints.getMinZoom() > 0) minZoomFactor = constraints.getMinZoom(); if (constraints.getMaxZoom() > 0) maxZoomFactor = constraints.getMaxZoom(); if (!constraints.getAllowZoom()) { // If allowZoom is false, clamp to the default zoom level. maxZoomFactor = minZoomFactor = constraints.getDefaultZoom(); } // Ensure minZoomFactor keeps the page at least as big as the viewport. if (pageRect.width() > 0) { float scaleFactor = viewport.width() / pageRect.width(); minZoomFactor = Math.max(minZoomFactor, zoomFactor * scaleFactor); if (viewport.width() > pageRect.width()) focusX = 0.0f; } if (pageRect.height() > 0) { float scaleFactor = viewport.height() / pageRect.height(); minZoomFactor = Math.max(minZoomFactor, zoomFactor * scaleFactor); if (viewport.height() > pageRect.height()) focusY = 0.0f; } maxZoomFactor = Math.max(maxZoomFactor, minZoomFactor); if (zoomFactor < minZoomFactor) { // if one (or both) of the page dimensions is smaller than the viewport, // zoom using the top/left as the focus on that axis. this prevents the // scenario where, if both dimensions are smaller than the viewport, but // by different scale factors, we end up scrolled to the end on one axis // after applying the scale PointF center = new PointF(focusX, focusY); viewportMetrics = viewportMetrics.scaleTo(minZoomFactor, center); } else if (zoomFactor > maxZoomFactor) { PointF center = new PointF(viewport.width() / 2.0f, viewport.height() / 2.0f); viewportMetrics = viewportMetrics.scaleTo(maxZoomFactor, center); } /* Now we pan to the right origin. */ viewportMetrics = viewportMetrics.clamp(); return viewportMetrics; }