代码之家  ›  专栏  ›  技术社区  ›  Mark Z.

形成无限滚动图像背景效果

  •  0
  • Mark Z.  · 技术社区  · 7 年前

    我正在努力使我认为将是一个很好的应用程序效果-一系列的图像(如墙纸)将不断滚动在背景中查看。我开始在Xamarin.Forms中创建这个原型,创建一个自定义控件。计划进行对角线翻译,但从最基本的方法开始,仍然很快遇到了一些问题,也就是说,它不是完全平滑的,因为它在这里和那里变得有点起伏(即使使用缓存和一个10kb的图像)和2)如果用户执行一个更复杂的操作,它可能会导致一个滞后和图像得到渲染更紧密地在一起比他们应该。有没有一种方法可以修复这种方法,使其尽可能平滑,并且不会干扰(或受到干扰)其他UI元素,或者有没有一种更优越的方法来处理类似的问题-有人处理过这种问题吗?请告诉我,谢谢。

    public class FlyingImageBackground : ContentView
    {
        public static readonly BindableProperty FlyingImageProperty =
          BindableProperty.Create(nameof(FlyingImage), typeof(ImageSource), typeof(FlyingImageBackground), default(ImageSource), BindingMode.TwoWay, propertyChanged: OnFlyingImageChanged);
    
        public ImageSource FlyingImage
        {
            get => (ImageSource)GetValue(FlyingImageProperty);
            set => SetValue(FlyingImageProperty, value);
        }
    
        private AbsoluteLayout canvas;
    
        public FlyingImageBackground()
        {
            this.canvas = new AbsoluteLayout()
                {
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    VerticalOptions = LayoutOptions.FillAndExpand
                };
    
            this.canvas.SizeChanged += Canvas_SizeChanged;
    
            Content = this.canvas;
        }
    
        ~FlyingImageBackground() => this.canvas.SizeChanged -= Canvas_SizeChanged;
    
        private static void OnFlyingImageChanged(BindableObject bindable, object oldValue, object newValue)
        {
            var control = (FlyingImageBackground)bindable;
            control.BringToLife();
        }
    
        private void BringToLife()
        {
            if (this.canvas.Width <= 0 || this.canvas.Height <= 0)
                return;
    
            Device.StartTimer(TimeSpan.FromSeconds(1), () =>
            {
                Device.BeginInvokeOnMainThread(async () =>
                {
                    await SendImageWave();
                });
    
                return this.canvas.IsVisible;
            });
        }
    
        private async Task SendImageWave()
        {
            var startingX = -100;
            var endingX = this.canvas.Width;
    
            if (endingX <= 0)
                return;
    
            endingX += 100;
    
            var yPositions = Enumerable.Range(0, (int)this.canvas.Height).Where(x => x % 90 == 0).ToList();
    
            var imgList = new List<CachedImage>();
    
            foreach (var yPos in yPositions)
            {
                var img = new CachedImage
                {
                    Source = FlyingImage,
                    HeightRequest = 50
                };
                imgList.Add(img);
    
                this.canvas.Children.Add(img, new Point(startingX, yPos));
            }
    
            await Task.WhenAll(
                imgList.Select(x => x.TranslateTo(endingX, 0, 10000)));
            //.Concat(imgList.Select(x => x.TranslateTo(startingX, 0, uint.MinValue))));
    
            imgList.ForEach(x =>
            {
                this.canvas.Children.Remove(x);
                x = null;
            });
    
            imgList = null;
        }
    
        private void Canvas_SizeChanged(object sender, EventArgs e)
        {
            BringToLife();
        }
    }
    

    只需将其与主要内容一起放入ContentPage的网格中: 例如。:

    <ContentPage.Content>
        <Grid>
            <controls:FlyingImageBackground FlyingImage="fireTruck.png" />
    
            <StackLayout HorizontalOptions="Center">
                <Button
                    Text="I'm a button!" />
                <Label
                    FontAttributes="Bold,Italic"
                    Text="You're a good man, old sport!!!"
                    TextDecorations="Underline" />
            </StackLayout>
        </Grid>
    
    </ContentPage.Content>
    
    0 回复  |  直到 7 年前
        1
  •  0
  •   Mark Z.    7 年前

    改用SkiaSharp,效果更好。动画看起来很平滑,如果流被打断,图像会保持适当的距离。在第一稿中,我还使用了内置的Xamarin动画,这使我无法确定何时运行它。即使页面不再在屏幕上,IsVisible prop也将保持为true,因此在这个新版本中,需要绑定到一个属性,该属性告诉我页面是否处于活动状态(基于它何时被导航到或导航离开),如果不是,则停止动画。目前这还只是处理水平滚动效果。希望其他人觉得它有用,任何其他的改进将是受欢迎的,请评论/张贴一个答案!

    [DesignTimeVisible(true)]
    public class FlyingImageBackgroundSkia : ContentView
    {
        public static readonly BindableProperty IsActiveProperty =
            BindableProperty.Create(
                nameof(IsActive),
                typeof(bool),
                typeof(FlyingImageBackground),
                default(bool),
                BindingMode.TwoWay,
                propertyChanged: OnPageActivenessChanged);
    
        private SKCanvasView canvasView;
        private SKBitmap resourceBitmap;
        private Stopwatch stopwatch = new Stopwatch();
    
        // consider making these bindable props
        private float percentComplete;
        private float imageSize = 40;
        private float columnSpacing = 100;
        private float rowSpacing = 100;
        private float framesPerSecond = 60;
        private float cycleTime = 1; // in seconds, for a single column
    
        public FlyingImageBackgroundSkia()
        {
            this.canvasView = new SKCanvasView();
            this.canvasView.PaintSurface += OnCanvasViewPaintSurface;
            this.Content = this.canvasView;
    
            string resourceID = "XamarinTestProject.Resources.Images.fireTruck.png";
            Assembly assembly = GetType().GetTypeInfo().Assembly;
    
            using (Stream stream = assembly.GetManifestResourceStream(resourceID))
            {
                this.resourceBitmap = SKBitmap.Decode(stream);
            }
        }
    
        ~FlyingImageBackgroundSkia() => this.resourceBitmap.Dispose();
    
        public bool IsActive
        {
            get => (bool)GetValue(IsActiveProperty);
            set => SetValue(IsActiveProperty, value);
        }
    
        private static async void OnPageActivenessChanged(BindableObject bindable, object oldValue, object newValue)
        {
            var control = (FlyingImageBackgroundSkia)bindable;
            await control.AnimationLoop();
        }
    
        private async Task AnimationLoop()
        {
            this.stopwatch.Start();
    
            while (IsActive)
            {
                this.percentComplete = (float)(this.stopwatch.Elapsed.TotalSeconds % this.cycleTime) / this.cycleTime; // always between 0 and 1
                this.canvasView.InvalidateSurface(); // trigger redraw
                await Task.Delay(TimeSpan.FromSeconds(1.0 / this.framesPerSecond)); // non-blocking
            }
    
            this.stopwatch.Stop();
        }
    
        private void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
        {
            SKImageInfo info = args.Info;
            SKSurface surface = args.Surface;
            SKCanvas canvas = surface.Canvas;
    
            canvas.Clear();
    
            var xPositions = Enumerable.Range(0, info.Width + (int)this.columnSpacing).Where(x => x % (int)this.columnSpacing == 0).ToList();
            xPositions.Insert(0, -(int)this.columnSpacing);
    
            var yPositions = Enumerable.Range(0, info.Height + (int)this.rowSpacing).Where(x => x % (int)this.rowSpacing == 0).ToList();
            yPositions.Insert(0, -(int)this.rowSpacing);
    
            if (this.resourceBitmap != null)
            {
                foreach (var xPos in xPositions)
                {
                    var xPosNow = xPos + (this.rowSpacing * this.percentComplete);
                    foreach (var yPos in yPositions)
                    {
                        canvas.DrawBitmap(
                            this.resourceBitmap,
                            new SKRect(xPosNow, yPos, xPosNow + this.imageSize, yPos + this.imageSize));
                    }
                }
            }
        }
    }