在滚动条上添加视差效果

时间:2019-08-21 21:52:06

标签: xamarin.ios uiscrollview parallax

我有一个视图,该视图在顶部具有一个滚动视图和一个常规视图,现在它只是改变了图层的高程,因此当向下滚动滚动视图时,它会变为最高视图。

我想做得更好,并添加一个不错的淡入淡出效果,但是目前我无法使其平滑淡出。

这是我目前正在做的事情:

private void MainScrollViewOnScrolled(object sender, EventArgs e)
{
    if (!(sender is UIScrollView scrollView))
    {
        return;
    }

    var topViewHeight = vTopPanel.Bounds.Height;
    var scrollOffsetY = scrollView.ContentOffset.Y;

    var scrollIndicatorInsets = scrollView.ScrollIndicatorInsets;

    nfloat scrollIndicatorTop = 0;
    var scrollOffsetDelta = topViewHeight - scrollOffsetY;

    if (scrollOffsetDelta > 0)
    {
        scrollIndicatorTop = scrollOffsetDelta;
    }

    scrollIndicatorInsets.Top = scrollIndicatorTop;
    scrollView.ScrollIndicatorInsets = scrollIndicatorInsets;

    var generalInfoEnabled = scrollOffsetY == 0;

    if (generalInfoEnabled)
    {
        vTopPanel.Alpha = 0;
        vTopPanel.Transform = CGAffineTransform.MakeIdentity();
        UIView.Animate(0.3f, 0, UIViewAnimationOptions.CurveEaseInOut,
            () => {
                vTopPanel.Alpha = 1;
            },
            null
        );
    }
    else
    {
        vTopPanel.Alpha = 1;
        vTopPanel.Transform = CGAffineTransform.MakeIdentity();
        UIView.Animate(0.3f, 0, UIViewAnimationOptions.CurveEaseInOut,
            () => {
                vTopPanel.Alpha = 0;
            },
            null
        );
    }
}

它可以工作,但不是很好,当我向下拖动时它会消失,但是当我滚动回到顶部时,顶视图重新出现的时间会明显延迟。 Android有一个非常好的做视差效果的方法,希望有人可以以正确的方式引导我为iOS做它。

1 个答案:

答案 0 :(得分:1)

您可以更改vTopPanel.AlphascrollOffsetY。并通过visable的值使其为visable或不为scrollOffsetY

例如:

    private void MainScrollViewOnScrolled(object sender, EventArgs e)
    {
        if (!(sender is UIScrollView scrollView))
        {
            return;
        }

        var topViewHeight = vTopPanel.Bounds.Height;
        var scrollOffsetY = scrollView.ContentOffset.Y;

        var scrollIndicatorInsets = scrollView.ScrollIndicatorInsets;

        nfloat scrollIndicatorTop = 0;
        var scrollOffsetDelta = topViewHeight - scrollOffsetY;

        if (scrollOffsetDelta > 0)
        {
            scrollIndicatorTop = scrollOffsetDelta;
        }

        scrollIndicatorInsets.Top = scrollIndicatorTop;
        scrollView.ScrollIndicatorInsets = scrollIndicatorInsets;

        //you can custom the topViewAlpha  here 
        //nfloat topViewAlpha = scrollOffsetY / (this.View.Frame.Height -vTopPanel.Frame.Size.Height);

        nfloat topViewAlpha = scrollOffsetY / (vTopPanel.Frame.Size.Height);

        if (topViewAlpha >=1)
        {
            topViewAlpha = 1;
        }

        //To get the opposite effect
        topViewAlpha = 1 - topViewAlpha;


        vTopPanel.Alpha = topViewAlpha;
    }
}