Unity UI ScrollView内item内容完整显示 超框自动滑动

关键API

用unity提供的工具计算两个ui的相对坐标

bounds = RectTransformUtility.CalculateRelativeRectTransformBounds(Viewport, curClickItem.transform);

bounds的max是item顶部与viewport顶部的距离;
min是item底部与viewport顶部的距离;
插值可以直接计算;

完整代码如下

public void SetRect()
        {
            rectHeight = Viewport.rect.height;
            bounds = RectTransformUtility.CalculateRelativeRectTransformBounds(Viewport, curClickItem.transform);
            float offsetY = 0;
            if (bounds.max.y + rectHeight > rectHeight)
                offsetY = -1 * bounds.max.y;
            if (bounds.min.y + rectHeight < 0)
                offsetY = -1 * (bounds.min.y + rectHeight);

            var anchoredPosition = Content.anchoredPosition;
            anchoredPosition.y += offsetY;
            Content.anchoredPosition = anchoredPosition;
        }

你可能感兴趣的:(UI,unity,unity,ui)