1/* 2 * Copyright (C) 2015 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.support.design.widget; 18 19import android.graphics.Matrix; 20import android.graphics.Rect; 21import android.graphics.RectF; 22import android.view.View; 23import android.view.ViewGroup; 24import android.view.ViewParent; 25 26class ViewGroupUtils { 27 private static final ThreadLocal<Matrix> sMatrix = new ThreadLocal<>(); 28 private static final ThreadLocal<RectF> sRectF = new ThreadLocal<>(); 29 30 /** 31 * This is a port of the common 32 * {@link ViewGroup#offsetDescendantRectToMyCoords(android.view.View, android.graphics.Rect)} 33 * from the framework, but adapted to take transformations into account. The result 34 * will be the bounding rect of the real transformed rect. 35 * 36 * @param descendant view defining the original coordinate system of rect 37 * @param rect (in/out) the rect to offset from descendant to this view's coordinate system 38 */ 39 static void offsetDescendantRect(ViewGroup parent, View descendant, Rect rect) { 40 Matrix m = sMatrix.get(); 41 if (m == null) { 42 m = new Matrix(); 43 sMatrix.set(m); 44 } else { 45 m.reset(); 46 } 47 48 offsetDescendantMatrix(parent, descendant, m); 49 50 RectF rectF = sRectF.get(); 51 if (rectF == null) { 52 rectF = new RectF(); 53 sRectF.set(rectF); 54 } 55 rectF.set(rect); 56 m.mapRect(rectF); 57 rect.set((int) (rectF.left + 0.5f), (int) (rectF.top + 0.5f), 58 (int) (rectF.right + 0.5f), (int) (rectF.bottom + 0.5f)); 59 } 60 61 /** 62 * Retrieve the transformed bounding rect of an arbitrary descendant view. 63 * This does not need to be a direct child. 64 * 65 * @param descendant descendant view to reference 66 * @param out rect to set to the bounds of the descendant view 67 */ 68 static void getDescendantRect(ViewGroup parent, View descendant, Rect out) { 69 out.set(0, 0, descendant.getWidth(), descendant.getHeight()); 70 offsetDescendantRect(parent, descendant, out); 71 } 72 73 private static void offsetDescendantMatrix(ViewParent target, View view, Matrix m) { 74 final ViewParent parent = view.getParent(); 75 if (parent instanceof View && parent != target) { 76 final View vp = (View) parent; 77 offsetDescendantMatrix(target, vp, m); 78 m.preTranslate(-vp.getScrollX(), -vp.getScrollY()); 79 } 80 81 m.preTranslate(view.getLeft(), view.getTop()); 82 83 if (!view.getMatrix().isIdentity()) { 84 m.preConcat(view.getMatrix()); 85 } 86 } 87} 88