/// <summary> /// 设置锚点 /// </summary> public static void SetAnchorType(this RectTransform pRectTransform, RectTransformAnchorType pAnchorType) { if (pRectTransform == null) { return; } KeyValuePair <Vector2, Vector2> tKv = mAnchorTypeDic[pAnchorType]; Vector2 tAnchorMin = tKv.Key; Vector2 tAnchorMax = tKv.Value; pRectTransform.anchorMin = tAnchorMin; pRectTransform.anchorMax = tAnchorMax; }
/// <summary> /// 获取锚点位置 /// </summary> public static KeyValuePair <Vector2, Vector2> GetAnchorTypeValue(RectTransformAnchorType pAnchorType) { foreach (var tKv in mAnchorTypeDic) { RectTransformAnchorType tAnchorType = tKv.Key; if (tAnchorType != pAnchorType) { continue; } return(tKv.Value); } return(mAnchorTypeDic[RectTransformAnchorType.None]); }
/// <summary> /// 是否是标准锚点, 就是那九个点 /// </summary> public static bool IsStandAnchorType(this RectTransform pRectTransform) { RectTransformAnchorType tAnchorType = pRectTransform.GetAnchorType(); if (tAnchorType == RectTransformAnchorType.TopLeft || tAnchorType == RectTransformAnchorType.TopCenter || tAnchorType == RectTransformAnchorType.TopRight || tAnchorType == RectTransformAnchorType.MiddleLeft || tAnchorType == RectTransformAnchorType.MiddleCenter || tAnchorType == RectTransformAnchorType.MiddleRight || tAnchorType == RectTransformAnchorType.BottomLeft || tAnchorType == RectTransformAnchorType.BottomeCenter || tAnchorType == RectTransformAnchorType.BottomRight ) { return(true); } return(false); }
/// <summary> /// 获取锚点 /// </summary> public static RectTransformAnchorType GetAnchorType(this RectTransform pRectTransform) { if (pRectTransform == null) { return(RectTransformAnchorType.None); } foreach (var tKv in mAnchorTypeDic) { RectTransformAnchorType tAnchorType = tKv.Key; Vector2 tAnchorMin = tKv.Value.Key; Vector2 tAnchorMax = tKv.Value.Value; if (pRectTransform.anchorMin == tAnchorMin && pRectTransform.anchorMax == tAnchorMax) { return(tAnchorType); } } return(RectTransformAnchorType.None); }
//获取cell 的位置偏移, 目的是使其对位是content 的左上角 private Vector2 GetCellOffsetValue(RectTransform pCell) { #if UNITY_EDITOR if (pCell.IsStandAnchorType() == false) { Debug.LogError("cell 的锚点必须是标准的形式, 就是TopLeft, TopCenter ... ... 这种"); } #endif RectTransformAnchorType tAnchorType = pCell.GetAnchorType(); Vector2 tAnchorValue = RectTransformExtension.GetAnchorTypeValue(tAnchorType).Key; Vector2 tTLAnchorValue = RectTransformExtension.GetAnchorTypeValue(RectTransformAnchorType.TopLeft).Key; Vector2 tAnchorOffset = tTLAnchorValue - tAnchorValue; Vector2 tAnchorOffsetPos = new Vector2(mRectTransform.rect.width * tAnchorOffset.x, mRectTransform.rect.height * tAnchorOffset.y); Vector2 tTLPivotValue = new Vector2(0, 1); Vector2 tPivotOffset = pCell.pivot - tTLPivotValue; Vector2 tPivotOffsetPos = new Vector2(tPivotOffset.x * pCell.rect.width, tPivotOffset.y * pCell.rect.height); Vector2 tTotalOffsetPos = new Vector2(tAnchorOffsetPos.x + tPivotOffsetPos.x, tAnchorOffsetPos.y + tPivotOffsetPos.y); return(tTotalOffsetPos); }