Unity IMGUI ScrollView 将ScrollPosition转化为ScrollPercent

简介

Unity中的ScrollView存储的是ScrollPosition,在展示的内容大小发生变化时,ScrollPosition也会受到影响而改变,此时我们存储拖拽的百分比ScrollPercent,能够增加代码的鲁棒性。


代码


        private void Use()
        {
            ScrollPosition = TurnScrollPercent2Position(scrollPercent);
            // 开始滚动视图
            ScrollPosition = GUI.BeginScrollView(
                ContainerRect,
                ScrollPosition,
                ContentRect,
                false,
                false
            );

            scrollPercent = TurnScrollPosition2Percent(ScrollPosition);
        }


        private Vector2 TurnScrollPosition2Percent(Vector2 scrollPos)
        {
            Vector2 percent = Vector2.zero;

            var scrollRange = GetScrollRange();


            if (ContentRect.width > ContainerRect.width)
                percent.x = scrollPos.x / scrollRange.x;


            if (ContentRect.height > ContainerRect.height)
                percent.y = scrollPos.y / scrollRange.y;

            return percent;

        }





        private Vector2 TurnScrollPercent2Position(Vector2 percent)
        {
            Vector2 scrollPos = Vector2.zero;
            var scrollRange = GetScrollRange();


            if (ContentRect.width > ContainerRect.width)
                scrollPos.x = percent.x * scrollRange.x;


            if (ContentRect.height > ContainerRect.height)
                scrollPos.y = percent.y * scrollRange.y;


            scrollPos.x = Mathf.Round(scrollPos.x);
            scrollPos.y = Mathf.Round(scrollPos.y);
            return scrollPos;

        }

        private Vector2 GetScrollRange()
        {
            bool displayRightScrollBar = ContentRect.height > ContainerRect.height;
            bool displayBottomScrollBar = ContentRect.width > ContainerRect.width;

            var horizontalScrollRange = (ContentRect.width - ContainerRect.width);
            if (displayRightScrollBar)
                horizontalScrollRange += scrollBarWidth; //13

            var verticalScrollRange = (ContentRect.height - ContainerRect.height);
            if (displayBottomScrollBar)
                verticalScrollRange += scrollBarWidth;

            return new Vector2(horizontalScrollRange, verticalScrollRange);
        }
posted @ 2025-11-11 21:56  dewxin  阅读(3)  评论(0)    收藏  举报