简体   繁体   English

Java - 淡入淡出和显示图像的不同方法

[英]Java - Different ways to fade and disply images

I'm starting to learn Java and i came across an excersize where i need to fade away one image and display by fading in another image.我开始学习 Java,我遇到了一个 excersize,我需要淡出一个图像并通过淡入另一个图像来显示。

My solution to this excersize is to have one imageView and fading out the first image, then switching the image source to the second image and fading the imageView in so it should display the new image.我对这个 excersize 的解决方案是有一个 imageView 并淡出第一个图像,然后将图像源切换到第二个图像并将 imageView 淡入以便它应该显示新图像。 Doing that so it will display all the images i want by fading out then in with a new image.这样做它会通过淡出然后用新图像显示我想要的所有图像。

this is my code for the program:这是我的程序代码:

public void fade(View view){

    ImageView simpsonImageView = findViewById(R.id.simpsonsImageView);

    simpsonImageView.animate().alpha(0f).setDuration(3000);
    simpsonImageView.setImageResource(R.drawable.bart);
    simpsonImageView.animate().alpha(1f).setDuration(3000);
    simpsonImageView.animate().alpha(0f).setDuration(3000);
    simpsonImageView.setImageResource(R.drawable.lisa);
    simpsonImageView.animate().alpha(1f).setDuration(3000);
}

Now i have seen in the tutorial i'm learning from that the tutor used different imageView for each image.现在我在教程中看到我正在学习导师为每个图像使用不同的 imageView。 I wanted to know which solution is correct or at least acceptable amoung these two.我想知道这两个解决方案中哪个是正确的或至少是可以接受的。 Or it dosent really matter and that both solutions are fine.或者它真的很重要并且两种解决方案都很好。

There is one thing which you can only achieve when using two ImageView s: you can crossfade the two images so that the screen is never entirely empty.只有在使用两个ImageView时才能实现一件事:您可以对两个图像进行淡入淡出,以便屏幕永远不会完全空白。

In the context of your exercise however, you only want to exchange images sequentially.但是,在您的练习中,您只想按顺序交换图像。

From a performance point of view, one ImageView may be better than two because it will obviously take less memory and CPU time but I doubt that this will have a noticeable impact on modern devices.从性能的角度来看,一个ImageView可能比两个更好,因为它显然会占用更少的内存和 CPU 时间,但我怀疑这会对现代设备产生明显的影响。

So as long as you don't animate lots of pictures simultaneously (think of football teams instead of the Simpsons), both solutions are fine.因此,只要您不同时为大量图片制作动画(想想足球队而不是辛普森一家),两种解决方案都可以。

Please note that with your code as-is there will be no animation visible at all and the ImageView will appear to only show the second picture.请注意,使用您的代码原样将看不到任何动画,并且ImageView似乎只显示第二张图片。 This is because animate() triggers an animation but it does not wait until the animation is finished.这是因为animate()会触发动画,但不会等到动画完成。 So you need to work with an AnimationListener or use Handler.postDelayed() to swap pictures and start the next animation only as soon as the previous one is finished.因此,您需要使用AnimationListener或使用Handler.postDelayed()来交换图片并在前一个动画完成后才开始下一个动画。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM