关于图片适配问题

背景

在开发过程中可能会遇到动态加载图片显示在UI上,但是UI切图不规范,长款大小不一致,导致动态加载显示大小不同,这时候需要对加载好的Sprite依据外框大小进行动态调整长款。调整思想:设置一个外边框,图片为外边框的子对象,图片是否超框判断,同比放大缩小,填充外框,避免拉伸图片。

    /// <summary>
    /// 图片显示适配
    /// </summary>
    /// <param name="sp">目标图片</param>
    /// <param name="maxHeight">外框最大高度</param>
    /// <param name="maxWidth">外框最大宽度</param>
    /// <returns>返回目标图片适配后的长宽</returns>
    public Vector2 GetPrefectSpSize(Sprite sp, float maxHeight, float maxWidth)
    {
        Vector2 v2 = Vector2.zero;
         var height = maxHeight; 
        var width = maxWidth;
        var spHeight = sp.bounds.extents.y * sp.pixelsPerUnit * 2;
        var spWidth = sp.bounds.extents.x * sp.pixelsPerUnit * 2;
        if (spHeight == height && spWidth == width)
        {
            v2.x = width;
            v2.y = height;
            return v2;
        }

        if (spWidth > width || spHeight > width)
        {
            //存在超框值
            var lerpWidth = spWidth - width;
            var lerpHeight = spHeight - height;

            if (lerpWidth > lerpHeight)
            {
                var scale = spWidth / width;
                v2.x = width;
                v2.y = spHeight / scale;
            }
            else
            {
                var scale = spHeight / height;
                v2.x = spWidth / scale;
                v2.y = height;
            }
        }
        else
        {
            //不存在超框
            var lerpWidth = width - spWidth;
            var lerpHeight = height - spHeight;
            //依据差距最小的
            if (lerpWidth < lerpHeight)
            {
                var scale = width / spWidth;
                v2.x = width;
                v2.y = spHeight * scale;
            }
            else
            {
                var scale = height / spHeight;
                v2.x = spWidth * scale;
                v2.y = height;
            }
        }
        return v2;
    }

需要者自取Demo_002:
链接:https://pan.baidu.com/s/1CP4FLttldNHW-gW2zUrlDA
提取码:ncv6

posted @ 2020-11-24 10:44  低小调  阅读(128)  评论(0编辑  收藏  举报